定制模型活页夹用于下拉列表不选择正确的值
-
30-09-2019 - |
题
我创建了自己的自定义模型活页夹,以处理我视图中定义的部分下拉列表:
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()));
...
}
这很好地验证了模型更新时分配的部分的正确值,但是如果另一个属性未验证,则不会选择正确的值。
如果有人可以告诉我如何做到这一点,我会很感激。谢谢
解决方案
通过说:解决问题:
Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections.Select(s => new { Text = s.SectionName, Value = s.SectionID.ToString() }), "Value", "Text"), "-- Please Select --")
这个问题似乎围绕该部分是整数。当您将其转换为字符串时,一切正常。希望这可以帮助。
不隶属于 StackOverflow