0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.