如何使用DropDownList绑定到WebGrid razor asp net mvc 4内的模型?

经过几个小时的谷歌搜索和尝试不同的语法,我决定发布这个。 问题是我无法在webgrid中使用DropDownList。 考虑以下模型:

public class UsuariosModel { public int UserId { get; set; } public string UserName { get; set; } public string Nombres { get; set; } public string ApellidoPaterno { get; set; } public string ApellidoMaterno { get; set; } public string Titulo { get; set; } public string Telefono { get; set; } public string Email { get; set; } public bool Activo { get; set; } public string[] Roles { get; set; } public List TodosLosRoles { get; set; } } 

控制者:

  public ActionResult UsuariosRoles() { List model = new Metodos.Entidades().listaUsuarios(); if (model != null) { var roles = (SimpleRoleProvider)Roles.Provider; var allRoles = roles.GetAllRoles().Select(x => new SelectListItem{ Text = x, Value = x }).ToList(); foreach (UsuariosModel md in model) { md.Roles = roles.GetRolesForUser(md.UserName); md.TodosLosRoles = allRoles; } return View(model); } else { return new EmptyResult(); } } 

并且观点:

 @model List @{ Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.Title = "Roles de los Usuarios -Administración-"; var grid = new WebGrid(source: Model); } 

Asignar roles a usuarios

@using (Html.BeginForm()) { @grid.GetHtml( columns:grid.Columns( grid.Column("UserId", "Id de Usuario"), grid.Column("UserName", "Nombre de Usuario"), grid.Column("Nombres", "Nombre(s)"), grid.Column("Titulo", "Título"), grid.Column("ApellidoPaterno", "Apellido Paterno"), grid.Column("ApellidoMaterno", "Apellido Materno"), grid.Column("Telefono", "Teléfono"), grid.Column("Email", "Email"), grid.Column("TodosLosRoles", "Roles", format:(item)=>Html.DropDownList(item.UserId, Model[0].TodosLosRoles.Select(u => new SelectListItem{Text= u.Text, Value=u.Value}))), headerStyle:"headerActivate", rowStyle:"rowActivate", selectedRowStyle:"selectedActivate")) }

在这一行: grid.Column("TodosLosRoles", "Roles", format:(item)=>Html.DropDownList(item.UserId, Model[0].TodosLosRoles.Select(u => new SelectListItem{Text= u.Text, Value=u.Value}))),

我无法摆脱错误:“CS1973:’System.Web.Mvc.HtmlHelper没有名为DropDownList的适用方法,但似乎有一个名称的扩展方法。扩展方法不能被动态调度”

但我已经阅读了很多关于这个错误的内容,我无法理解为什么我会继续这样做。 毕竟我已经将DropDownList格式化为具有SelectListItems,而不是我。

请帮助我,我很生气。

更新

我也尝试了这个: grid.Column("TodosLosRoles", "Roles", format:(item)=>Html.DropDownList(item.UserId, (List)item.TodosLosRoles)),

但是我一直在收到错误,所以有人可以告诉我为什么即使转换到原始类型也无法修复它,错误清楚地说:

考虑转换动态参数或调用扩展方法而不使用扩展方法语法

那么我怎么称它为“没有扩展方法语法”?

请尝试以下格式:

 grid.Column( "TodosLosRoles", "Roles", format: item => Html.DropDownList(((int)item.UserId).ToString(), Model[0].TodosLosRoles) ) 

这有点废话,但WebGrid一般都是垃圾。 它依赖于弱动态类型,如果依赖于此组件,您可以忘记强类型和正确的视图模型。 如果你不是非常小心你传递的类型,准备施放地狱和潜在的运行时错误。