当我提交表单时,我遇到了这个错误,我很困惑,因为我在其他视图上使用了相同的方法,并且它可以完美地工作,只是在此视图上
我的模型
public class Usuario
{
[Required(ErrorMessage = "Ingrese una cedula")]
//[StringLength(8,MinimumLength = 8,ErrorMessage = "La cedula debe poseer 8 digitos")]
public int Id { get; set; }
[Required(ErrorMessage = "Ingrese un nombre")]
public string Nombre { get; set; }
[Required(ErrorMessage = "Ingrese un primer apellido")]
public string Apellido1 { get; set; }
[Required(ErrorMessage = "Ingrese segundo apellido")]
public string Apellido2 { get; set; }
[Required(ErrorMessage = "Ingrese un nombre de usuario")]
public string NombreUsuario { get; set; }
[Required(ErrorMessage = "Ingrese una contraseña")]
[DataType(DataType.Password)]
public string Contraseña { get; set; }
public int IdRol { get; set; }
public string Correo { get; set; }
public int Telefono { get; set; }
public bool Temporal { get; set; }
public string Mensaje { get; set; }
}
public class Rol
{
[AutoIncrement]
public int Id { get; set; }
public string Nombre { get; set; }
}
这是View
上的下拉列表中的代码 <div class="form-group">
<label class="control-label col-md-2">Rol</label>
<div class="col-md-10">
@Html.DropDownList("ddlRol", (IEnumerable<SelectListItem>)ViewBag.ddlRol,"Seleccione un rol", new { @class = "control-label-col-md-2" })
</div>
</div>
我的控制器
public ActionResult Crear()
{
var roles = mRol.ListarRoles();
ViewBag.ddlRol = new SelectList(roles, "Id", "Nombre");
return View();
}
单击提交按钮时,我遇到了错误'没有键'iEnumerable'的ViewData项目,它具有键'ddlrol'。'
我已经尝试了其他帖子的解决方案,但是他们没有工作,或者我不知道我在做错了什么,请有人向我解释吗?
您在下拉列表上缺少值的值。在下拉列表中,您必须始终具有文本和值变量。使用 @html.dropdownlistfor selectList的更好方法。
示例:查看
@Html.DropDownListFor(x => x.YourModel, new SelectList(ViewBag.customValue, "Text", "Value"), new { htmlAttributes = new { @class = "form-control" } })
示例:控制器
List<SelectListItem> listForSelect = new List<SelectListItem>();
listForSelect.Add(new SelectListItem { Text = "Your text", Value = "Your value" });
ViewBag.customValue = listForSelect;