我创建了自己的自定义模型绑定器来处理在我的视图中定义的 Section DropDownList :
Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections, "SectionID", "SectionName"), "-- Please Select --")
这是我的模型活页夹:
public class SectionModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (bindingContext.ModelType.IsAssignableFrom(typeof(Section)) && value != null)
{
if (Utilities.IsInteger(value.AttemptedValue))
return Section.GetById(Convert.ToInt32(value.AttemptedValue));
else if (value.AttemptedValue == "")
return null;
}
return base.BindModel(controllerContext, bindingContext);
}
}
现在在我的控制器中,我可以说:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
var category = new Category();
if (!TryUpdateModel(category, "Category")
return View(new CategoryForm(category, _sectionRepository().GetAll()));
...
}
这很好地验证并在更新模型时为该部分分配正确的值,但是如果另一个属性未验证,则它不会选择正确的值。
如果有人能告诉我如何做到这一点,我将不胜感激。谢谢