将自定义HTML Helper添加到MVC项目
我一直在浏览网页试图找到一个很好的示例/教程,详细说明如何为我的MVC 3 Razor应用程序创建和使用我自己的自定义HTML帮助程序我发现这个如下所示
在ASP.NET MVC 3中添加自己的HtmlHelper
我已经创建了一个类(稍微修剪了一下)
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; namespace MyWebApp { public static class ExtensionMethods { public static MvcHtmlString StateDropDownListFor (this HtmlHelper html, Expression<Func> expression) { Dictionary stateList = new Dictionary() { {"AL"," Alabama"}, {"AK"," Alaska"}, {"AZ"," Arizona"}, {"AR"," Arkansas"} }; return html.DropDownListFor(expression, new SelectList(stateList, "key", "value")); } } }
到现在为止还挺好,
在我的控制器内部,我还添加了参考
using System.Web.Mvc.Html;
现在在我看来,我有以下内容
@Html.StateDropDownList(x => x.State)
但是我收到以下错误
System.web.mvc.htmlhelper<system.collections.generic.list> does not contain a definition for StateDropDownList and no extension method StateDropDownList acception a first argument of type system.web.mvc.htmlhelper<System.Collections.Generic.List> could be found(Are you missing a using directive of an assembly reference?)
有人可以告诉我这里做错了什么。
您应该在视图中包含命名空间:
@using MyWebApp
或者,您可以从web.config为所有视图导入此命名空间。
我认为更简单的选择是执行以下操作:1。像往常一样创建一个视图,像往常一样将助手放在其中,并根据需要混合使用代码和html。 2.将视图移动到App_Code文件夹。 3.在所有视图中获取帮助(请注意_MyHelpers是App_Code文件夹中视图的名称):
@_MyHelpers.JQMRadioTrueFalse("Voice Mail on your Home Phone?", "HomePhoneHasAnswerPhone", Model.TrueFalse, t.HomePhoneHasAnswerPhone)
这将是App_Code文件夹中的视图示例,该视图在任何视图上访问,如上所示:
@helper JQMRadioList(string Legend, string RadioListName, List options, bool Horizontal = false, string CurrentSelection = "") { }
- 查看数据字典覆盖ASP.NET MVC中的模型数据
- ASP.NET MVC按请求注入
- 将特殊字符转换为正常
- @ Html.ValueFor(x => x.PropertyName)和@ Model.PropertyName之间的区别是什么?
- NamedScopes Ninject绑定和异步(线程)
- asp.net mvc中的模型绑定通用列表为null
- 带有枚举的MVC3 RadioButtonFor
- 在Entity Framework支持的Web API 2 POST调用中返回一个对象以及409 Conflict错误?
- 在MVC中,可以更改@ Html.DropDownListFor中每个列表项的字体(创建类似于MS office的字体下拉列表