0

我正在艰难地学习 ASP.NET MVC。我最近编写了一个扩展方法,可以帮助我决定是否应该选择下拉列表中的项目。我知道 HTML 辅助方法。我只是想了解这里的工作原理。无论如何,我目前有以下代码:

<select id="Gender">
  <option value="-1" @Html.IsSelected(Convert.ToString(ViewBag.Gender), "-1")>Unspecified</option>
  <option value="0" @Html.IsSelected(Convert.ToString(ViewBag.Gender), "0")>Male</option>
  <option value="1" @Html.IsSelected(Convert.ToString(ViewBag.Gender), "1")>Female</option>
</select>

当我执行这个时,我在视图上得到一个编译错误,上面写着:

 CS1973: 'System.Web.Mvc.HtmlHelper<dynamic>' has no applicable method named 'IsSelected' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

我的问题是,如何使用 ViewBag 中的值执行扩展方法?如果我用硬编码值替换 ViewBag.Gender ,它就可以工作。这让我认为问题在于 ViewBag 是一种动态类型。但是,我还有什么其他选择?

4

2 回答 2

1

我也有同样的问题。改用 ViewData .. 例如,替换

 @using (Html.BeginSection(tag:"header", htmlAttributes:@ViewBag.HeaderAttributes)) {}

@using (Html.BeginSection(tag:"header", htmlAttributes:@ViewData["HeaderAttributes"])) {}

它工作正常;)

于 2015-07-21T17:24:24.537 回答
0

这可能会有所帮助:

public static class HtmlHelperExtensions
    {
public static MvcHtmlString GenderDropDownList(this HtmlHelper html, string name, int selectedValue, object htmlAttributes = null)
        {
            var dictionary = new Dictionary<sbyte, string>
            {
                { -1, "Unspecified" },
                { 0, "Male" },
                { 1, "Female" },
            };

            var selectList = new SelectList(dictionary, "Key", "Value", selectedValue);
            return html.DropDownList(name, selectList, htmlAttributes);
        }

        public static MvcHtmlString GenderDropDownListFor<TModel>(this HtmlHelper<TModel> html, Expression<Func<TModel, bool?>> expression, object htmlAttributes = null)
        {
            var dictionary = new Dictionary<sbyte, string>
            {
                { -1, "Unspecified" },
                { 0, "Male" },
                { 1, "Female" },
            };

            var selectedValue = ModelMetadata.FromLambdaExpression(
                expression, html.ViewData
            ).Model;

            var selectList = new SelectList(dictionary, "Key", "Value", selectedValue);
            return html.DropDownListFor(expression, selectList, htmlAttributes);
        }
}

像这样使用它:

@Html.GenderDropDownList("Gender", 0)

或者:

@Html.GenderDropDownListFor(m => m.Gender)
于 2013-03-10T08:51:19.757 回答