HtmlExtensions寻找这个HtmlHelper <tmodel> htmlHelper </tmodel>

时间:2011-06-23 21:14:24

标签: asp.net-mvc-3 htmlextensions

我试图在我的mvc项目中添加一些htmlextensions。当我尝试使用它们时,他们都期待这个HtmlHelper htmlHelper参数?但根据所有的例子,这些都不是预期的......我做错了什么?

public static string RadioButtonListFor(this HtmlHelper htmlHelper,Expression&gt; expression,String tagBase)其中TModel:class         {             return htmlHelper.RadioButtonListFor(expression,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();
    }

2 个答案:

答案 0 :(得分:0)

您正在为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

答案 1 :(得分:0)

我写了一篇文章,内容涉及为HtmlHelper.DropDownList帮助器创建扩展方法。检查一下......它可能会有所帮助。我介绍了DropDownListDropDownListFor方法,并在Razor视图文件和web.config中包含对扩展方法类的命名空间的引用。

Populate html select lists from data in a view model in an ASP.NET MVC 3 application