我尝试在我的mvc项目中添加一些htmlextension。当我尝试使用它们时,它们都期望有一个this HtmlHelper htmlHelper参数?但根据所有的例子,这些都不是预期的..我做错了什么?
公共静态字符串RadioButtonListFor(this expression htmlHelper,Expression> expression,string tagBase) where TModel :htmlHelper.RadioButtonListFor{ return htmlHelper.RadioButtonListFor( HtmlHelper,tagBase,null);}
public static string RadioButtonListFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, RadioButtonListViewModel>> expression, String tagBase, object htmlAttributes) where TModel : class
{
return htmlHelper.RadioButtonListFor(expression, tagBase, new RouteValueDictionary(htmlAttributes));
}
public static string RadioButtonListFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, RadioButtonListViewModel>> expression, String tagBase, IDictionary<string, object> htmlAttributes) where TModel : class
{
var inputName = tagBase;
RadioButtonListViewModel radioButtonList = GetValue(htmlHelper, expression);
if (radioButtonList == null)
return String.Empty;
if (radioButtonList.ListItems == null)
return String.Empty;
var containerTag = new TagBuilder("td");
containerTag.MergeAttribute("id", inputName + "_Container");
foreach (var item in radioButtonList.ListItems)
{
var radioButtonTag = RadioButton(htmlHelper, inputName, new SelectListItem { Text = item.Text, Selected = item.Selected, Value = item.Value.ToString() }, htmlAttributes);
containerTag.InnerHtml += radioButtonTag;
}
return containerTag.ToString();
}发布于 2011-06-24 07:20:56
您正在为HtmlHelper类编写扩展方法。当你想使用你的扩展方法时,你必须导入你的扩展方法所在的命名空间。
例如,假设RadioButtonListFor在MyNamespace中
namespace MyNamespace
{
public static class HtmlExtensions
{
public static string RadioButtonListFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, RadioButtonListViewModel>> expression, String tagBase, object htmlAttributes) where TModel : class
{
return htmlHelper.RadioButtonListFor(expression, tagBase, new RouteValueDictionary(htmlAttributes));
}
}
}现在,在您的视图中,您必须导入MyNamespace才能使用此扩展方法。您可以通过在页面顶部指定名称空间来导入Razor中的名称空间。
@using MyNamespace发布于 2011-06-24 07:33:10
我写了一篇关于为HtmlHelper.DropDownList助手创建扩展方法的文章。检查一下,out...it可能会有所帮助。我介绍了DropDownList和DropDownListFor方法,并在Razor视图文件和web.config中都包含了对扩展方法类的名称空间的引用。
Populate html select lists from data in a view model in an ASP.NET MVC 3 application
https://stackoverflow.com/questions/6460669
复制相似问题