Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top