创建自定义控件mvc3 [英] create custom controls mvc3

查看:61
本文介绍了创建自定义控件mvc3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚开始摆脱MVC3的束缚,并想要开始构建一些我可以放入视图中的自定义控件.具体来说,我希望能够放入一些html表单控件,这些控件会自动添加一些javascript进行验证.

Just starting to get the hang of MVC3 and want to start building out some custom controls that I can just drop into a view. Specifically I want to be able to drop in some html form controls that will automatically add some javascript for validation.

我想要这样的东西

@Html.VTextBox("MyTextBox","",new {@vType="PhoneNumber", @vMessage="You Must Enter a Phone Number" })

呈现页面时,我希望它搜索我创建的任何自定义元素,然后放入适当的JavaScript来验证客户端.我使用了用于自定义控件的asp.net网络表单进行了与此非常相似的操作,例如

when the page is rendered, I'd want it to search for any custom elements I create then drop in the appropriate javascript to validate client side. I did something very similar to this with asp.net web forms for custom controls ie

<ucc:VTextBox ID="MyTextBox" runat="server" message="You must fill this in" />

只是想知道MVC3是否提供相同的可扩展性.您可以提供的任何资源或建议,将不胜感激.

just wondering if MVC3 offers the same extensibility. Any resources or advice you can provide would be greatly appreciated.

TIA

推荐答案

首先,您需要研究扩展方法,更具体地说,是如何为HtmlHelper类创建扩展方法,以便编写类似以下的代码您上面显示的示例.

To start off with, you'll need to look into extension methods and more specifically, how to create extension methods for the HtmlHelper class so you could write code like the example you've shown above.

对于上面显示的示例,您可以编写如下代码:

For the example you've shown above, you could write code like this:

public MvcHtmlString VTextBox(string name, object value, object htmlAttributes)
{
    StringBuilder html = new StringBuilder();

    // Build your html however you want
    // Here's a simple example that doesn't
    // take into account your validation needs
    html.AppendFormat("input type=\"text\" name=\"{0}\" value=\"{1}\" />", name, value);

    return MvcHtmlString(html.ToString());   
}

然后在您的视图中可以像上面这样使用上面的示例:

Then in your view you can use the example above like so:

@Html.VTextBox("MyTextBox","",new {@vType="PhoneNumber", @vMessage="You Must Enter a Phone Number" })

注意:您需要将扩展​​方法所在的名称空间导入视图.最简单的方法是在视图顶部放置@using ExtensionMethodNamespace.您可以通过摆弄web.config(可能是Global.asax),将名称空间自动导入到所有视图中.

NOTE: You'll need to import the namespace the extension method is in to your view. Simplest method, put a @using ExtensionMethodNamespace at the top of your view. You can make the namespace automatically imported to all your views by fiddling with the web.config (and maybe the Global.asax).

附录:请注意以下RPM1984的注释,在该注释中,他建议使用TagBuilder代替StringBuilder,这是合理的建议,因为这是TagBuilder专门设计的方案.他还提到要在模型中强力键入帮助程序,这也是很好的建议.

ADDENDUM: Please note RPM1984's comment below where he advises to use TagBuilder in place of StringBuilder which is sound advice since this is the exact scenario TagBuilder was designed for. He also mentions strong typing the helper to the model which is also great advice.

这篇关于创建自定义控件mvc3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆