Sosi
Sosi

Reputation: 2578

MVC custom model binder issue

I have a textbox in my view that i want to receive the value as a List of strings.

As example, if anybody enters: tag1,tag2,tag3... receive a List with 3 elements.

I did a custom model binder, but im still receiving from the post the string instead the List.

This is the stuff that i did:

This is my Model:

public class BaseItem
{
    [Required]
    [StringLength(100)]
    public string Name
    {
       get;
       set;
    }
    public IList<string> RelatedTags
    {
       get;
       set;
    }

}

My typed view with the model above:

<% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary("Please complete in a right way the fields below.") %>

        <fieldset>
            <legend>Fields</legend>
            <div class="editor-field">
                <%: Html.LabelFor(e => e.Name)%>
                <%: Html.TextBoxFor(e => e.Name)%>
                <%: Html.ValidationMessageFor(e => e.Name)%>
            </div>
            <div class="editor-field">
                <%: Html.LabelFor(e => e.RelatedTags)%>
                <%: Html.TextBoxFor(e => e.RelatedTags)%>
                <%: Html.ValidationMessageFor(e => e.RelatedTags)%>
            </div>
            <p>
                <input type="submit" />
            </p>
        </fieldset>

    <% } %>

My custom model binder:

public class TagModelBinder:DefaultModelBinder
{
    protected override object GetPropertyValue(
        ControllerContext controllerContext, 
        ModelBindingContext bindingContext, 
        System.ComponentModel.PropertyDescriptor propertyDescriptor, 
        IModelBinder propertyBinder)
    {
       object value = base.GetPropertyValue(
                          controllerContext, 
                          bindingContext, 
                          propertyDescriptor, 
                          propertyBinder);
       object retVal = value;
       if (propertyDescriptor.Name == "RelatedTags")
       {                 
           retVal = bindingContext.ValueProvider.GetValue("RelatedTags")
                        .RawValue.ToString().Split(',').ToList<string>();
       }
       return retVal;
    }
}

I registered my Custom model binder on my Global.asax.cs file:

ModelBinders.Binders.Add(typeof(string), new TagModelBinder());

The issue that im having is that never enters in the method "GetPropertyValue" of my custom binder.

For sure im missing anything. Could you give me a hand?

Upvotes: 3

Views: 1175

Answers (1)

tarn
tarn

Reputation: 2182

Try binding to typeof IList as that is the type you are trying to bind too.

ModelBinders.Binders.Add(typeof(IList<string>), new TagModelBinder());

Hope it helps.

Upvotes: 3

Related Questions