开发者

Custom Model Binder for DropDownList not Selecting Correct Value

开发者 https://www.devze.com 2023-01-14 16:31 出处:网络
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\", \"Secti

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 : DefaultMo开发者_如何学CdelBinder 
{ 
    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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消