ModelBinding asp.net MVC List

I have the following class:

public class Movie
{
   string Name get; set;
   string Director get;  set;
   IList<String> Tags get; set;
}

How do I bind the tags properties? to a simple imput text, separated by commas. But only to the controller I’am codding, no for the hole application.
Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You could start with writing a custom model binder:

public class MovieModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
    {
        if (propertyDescriptor.Name == "Tags")
        {
            var values = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);
            if (values != null)
            {
                value = values.AttemptedValue.Split(',');
            }
        }
        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
    }
}

and then applying it to a particular controller action which is supposed to receive the input:

public ActionResult Index([ModelBinder(typeof(MovieModelBinder))] Movie movie)
{
    // The movie model will be correctly bound here => do some processing
}

Now when you send the following GET request:

/index?tags=tag1,tag2,tag3&name=somename&director=somedirector

Or POST request with an HTML <form>:

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.Name)
        @Html.EditorFor(x => x.Name)
    </div>
    <div>
        @Html.LabelFor(x => x.Director)
        @Html.EditorFor(x => x.Director)
    </div>
    <div>
        @Html.LabelFor(x => x.Tags)
        @Html.TextBoxFor(x => x.Tags)
    </div>
    <input type="submit" value="OK" />
}

The Movie model should be bound correctly in the controller action and only inside this controller action.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x