1

我已经创建了自己的自定义模型绑定来处理我的观点限定的区间的DropDownList:自定义模型绑定的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())); 

    ... 
} 

这很好地验证并为secti正确的值on在模型更新时分配,但如果另一个属性不验证,它不会选择正确的值。

我会很感激,如果有人能告诉我如何做到这一点。说解决了由于

回答

0

问题:

Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections.Select(s => new { Text = s.SectionName, Value = s.SectionID.ToString() }), "Value", "Text"), "-- Please Select --") 

这个问题似乎解决围绕SectionID为整数。当你将它转换为字符串时,一切正常。希望这可以帮助。