2013-02-18 38 views
0

我在学习ASP.NET MVC时蹒跚着学习。我最近编写了一个扩展方法,可以帮助我确定是否应该选择下拉列表中的项目。我知道HTML帮助器方法。我只是想学习这里的工作方式。不管怎么说,我现在有下面的代码:在带有ASP.NET MVC的RAZOR中使用带扩展方法的ViewBag

<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是一种动态类型。但是,我还有什么其他选择?

+0

你能后的IsSelected扩展?这可能会帮助我给你一个更好的建议 – Matt 2013-03-10 08:39:47

回答

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) 
0

我最好了同样的问题。 使用ViewData的,而不是.. 例如,与

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

它工作正常更换

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

;)

相关问题