我正在尝试验证我的模型。它每次都是假的。下面是我的控制器,视图和型号代码。有没有人有这个想法?
我的控制器就像:
[HttpPost]
public ActionResult Registration(Register reg)
{
if (ModelState.IsValid)
{
//some code
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
//some code
}
}
我的观点就像
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data", id = "ArcherRegistration" }))
{
<body>
<legend>Details</legend>
<div class="top">
@Html.Label("Select School: ")
@*@Html.DropDownListFor(model => model.lstSchool, new SelectList(Model.lstSchool, "Key", "Value"),new { @class = "defaultTextBox", @id = "ddlSchools"})*@
@Html.DropDownListFor(m => m.selectedSchool,
new SelectList(Model.lstSchool, "Key", "Value"),"--Select--",
new { @class = "defaultTextBox", @id = "ddlSchools"})
@Html.ValidationMessageFor(model => model.selectedSchool,"",new {@class="field-validation-error"})
</div>
<div class="top">
@Html.Label("Enter Name: ")
@Html.TextBoxFor(model=>model.Name, "",new { @class = "defaultTextBox",@maxlength = "50"})
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="top">
@Html.Label("Select Archer Gender: ")
@Html.DropDownListFor(m => m.selectedGender,
new SelectList(Model.Gender, "Value", "Text"), "--Select--",
new {@class = "defaultTextBox"})
@Html.ValidationMessageFor(model => model.selectedGender)
</div>
</body>
}
我的模特是:
public class Register
{
public int tourID {get ; set;}
[Required]
[Display(Name = "School")]
public string selectedSchool { get; set; }
public Dictionary<int, string> lstSchool { get; set; }
[Required]
[MaxLength(50, ErrorMessage = "Limit exceeds 50")]
[RegularExpression("^[a-zA-Z ]*$", ErrorMessage = "Only characters are allowed")]
[Display(Name = "Archer Name")]
public string ArcherName { get; set; }
[Required]
[Display(Name = "Gender")]
public string selectedGender { get; set; }
public IEnumerable<SelectListItem> Gender { get; set; }
[Required]
[Display(Name = "Grade")]
public string selectedGrade { get; set; }
public Dictionary<int, string> lstGrade { get; set; }
}
即使我填写模型中的所有细节,我的模型也不会验证。它抛出System.InvalidOperationException:参数转换错误。
答案 0 :(得分:1)
下拉列表需要IEnumerable<SelectListItem>
,但这是一个接口,而不是一个可靠的实现......例如&#34;我序列化时应该创建什么样的IEnumerable
?我不知道!&#34;
将该成员更改为List<SelectListItem>
[Required]
[Display(Name = "Gender")]
public string selectedGender { get; set; }
public List<SelectListItem> Gender { get; set; }
由于该列表是只读数据,因此根本无法将其发送回服务器。只需将其放入ViewBag
即可。其他两个基于Dictionary
的成员也是如此。
只需确保在视图中将ViewBag属性强制转换为正确的类型,否则它将假定object
并因其他错误而失败:)