我在编辑视图中有两个DropDownListFor元素。即使在下拉列表中选择了值,它也会在我尝试提交视图时触发DropDownListFor必需字段验证。
public class propertyTypeModel
{
public int type_id { get; set; }
[Required(ErrorMessage = "Property Type Required")]
[Display(Name = "Type")]
public string property_type { get; set; }
}
public class propertyStatusModel
{
public int status_id { get; set; }
[Required(ErrorMessage = "Status Required")]
[Display(Name = "Status")]
public string property_status { get; set; }
}
public class propertyModel
{
public int id { get; set; }
[Display(Name = "Property Type")]
public propertyTypeModel property_type { get; set; }
[Display(Name = "Property Type")]
[Required]
public List<propertyTypeModel> property_type_lst { get; set; }
[Display(Name = "Property Status")]
public propertyStatusModel property_status { get; set; }
[Display(Name = "Property Status")]
[Required]
public List<propertyStatusModel> property_status_lst { get; set; }
}
public ActionResult Edit(int id)
{
rep=new propertyRepository();
propertyModel model = new propertyModel();
model.id = id;
model.property_type_lst = getPropertyTypes();//load dropdown values
model.property_status_lst = getPropertyStatus();//load dropdown values
return View(model);
}
[HttpPost]
public ActionResult Edit(int id, propertyModel model)
{
try
{
model.property_type_lst = getPropertyTypes();
model.property_status_lst = getPropertyStatus();
model.property_owner_lst = getPropertyOwners();
if (ModelState.IsValid)
{
rep = new propertyRepository();
rep.Update(model);
return RedirectToAction("Index");
}
return View(model);
}
catch
{
return View();
}
}
@model RealEstateApp.Models.propertyModel
<div class="editor-label">
@Html.LabelFor(model => model.property_type_lst)
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.property_type.type_id, new SelectList(Model.property_type_lst, "type_id", "property_type"),"Select Below...")
@Html.ValidationMessageFor(model => model.property_type_lst)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.property_status_lst)
</div>
<div class="editor-field">
@Html.DropDownListFor(x => x.property_status.status_id, new SelectList(Model.property_status_lst, "status_id", "property_status"),"Select Below...")
@Html.ValidationMessageFor(model => model.property_status_lst)
</div>
答案 0 :(得分:0)
尝试
<div class="editor-field">
@Html.DropDownListFor(model.property_type_lst, new SelectList(Model.property_type_lst, "type_id", "property_type"),"Select Below...", new {id = Model.property_type.type_id})
@Html.ValidationMessageFor(model => model.property_type_lst)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.property_status_lst)
</div>
<div class="editor-field">
@Html.DropDownListFor(model.property_status_lst, new SelectList(Model.property_status_lst, "status_id", "property_status"),"Select Below...", new {id = Model.property_status.status_id})
@Html.ValidationMessageFor(model => model.property_status_lst)
</div>