首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找此HtmlHelper<TModel> htmlHelper的HtmlExtensions

查找此HtmlHelper<TModel> htmlHelper的HtmlExtensions
EN

Stack Overflow用户
提问于 2011-06-24 05:14:24
回答 2查看 1.6K关注 0票数 0

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

公共静态字符串RadioButtonListFor(this expression htmlHelper,Expression> expression,string tagBase) where TModel :htmlHelper.RadioButtonListFor{ return htmlHelper.RadioButtonListFor( HtmlHelper,tagBase,null);}

代码语言:javascript
复制
    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();
    }
EN

回答 2

Stack Overflow用户

发布于 2011-06-24 07:20:56

您正在为HtmlHelper类编写扩展方法。当你想使用你的扩展方法时,你必须导入你的扩展方法所在的命名空间。

例如,假设RadioButtonListForMyNamespace

代码语言:javascript
复制
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中的名称空间。

代码语言:javascript
复制
@using MyNamespace
票数 0
EN

Stack Overflow用户

发布于 2011-06-24 07:33:10

我写了一篇关于为HtmlHelper.DropDownList助手创建扩展方法的文章。检查一下,out...it可能会有所帮助。我介绍了DropDownListDropDownListFor方法,并在Razor视图文件和web.config中都包含了对扩展方法类的名称空间的引用。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6460669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档