自定义模型绑定的DropDownList的选择不正确的价值

问题描述:

我已经创建自己的自定义模型绑定来处理我的观点定义为一个章节的DropDownList:

i've created my own custom model binder to handle a Section DropDownList defined in my view as:

Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections, "SectionID", "SectionName"), "-- Please Select --")

这是我的模型绑定:

And here is my model binder:

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); 
    } 
}

现在我的控制器内我可以说:

Now within my controller i can say:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    var category = new Category();

    if (!TryUpdateModel(category, "Category")
        return View(new CategoryForm(category, _sectionRepository().GetAll()));

    ...
}

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

This validates nicely and the correct value for the section is assigned when the model is updated, however it does not select the correct value if another property doesn't validate.

我倒是AP preciate,如果有人可以告诉我如何做到这一点。谢谢

I'd appreciate it if someone could show me how to do this. Thanks

问题说解决:

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为整数。当你将它转换为字符串一切工​​作正常。希望这有助于。

The issue seems to resolve around the SectionID being an integer. When you convert it to a string everything works fine. Hope this helps.