Custom Model Binder for DropDownList not Selecting Correct Value

旧巷老猫 提交于 2020-01-24 19:33:09

问题


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.

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


回答1:


Problem solved by saying:

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

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



来源:https://stackoverflow.com/questions/3642870/custom-model-binder-for-dropdownlist-not-selecting-correct-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!