在带有ASP.NET MVC的RAZOR中使用带有扩展方法的ViewBag

在带有ASP.NET MVC的RAZOR中使用带有扩展方法的ViewBag,razor,asp.net-mvc-4,extension-methods,Razor,Asp.net Mvc 4,Extension Methods,我正在努力学习ASP.NETMVC。我最近写了一个扩展方法,帮助我决定是否应该选择下拉列表中的项目。我知道HTML助手方法。我只是想了解这里的情况。无论如何,我目前有以下代码: <select id="Gender"> <option value="-1" @Html.IsSelected(Convert.ToString(ViewBag.Gender), "-1")>Unspecified</option> <option value="0"

我正在努力学习ASP.NETMVC。我最近写了一个扩展方法,帮助我决定是否应该选择下拉列表中的项目。我知道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.
CS1973:'System.Web.Mvc.HtmlHelper'没有名为'IsSelected'的适用方法,但似乎有一个同名的扩展方法。无法动态调度扩展方法。考虑在不使用扩展方法语法的情况下强制转换动态参数或调用扩展方法。

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

以下是一些可能有用的方法:

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);
        }
}
或:

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

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


它工作得很好;)

你能把选定的分机发出去吗?那可能会帮我给你一个更好的建议
@Html.GenderDropDownListFor(m => m.Gender)
 @using (Html.BeginSection(tag:"header", htmlAttributes:@ViewBag.HeaderAttributes)) {}
@using (Html.BeginSection(tag:"header", htmlAttributes:@ViewData["HeaderAttributes"])) {}