开发者

ModelBinding asp.net MVC List

I have the following class:

public class Movie
{
   s开发者_如何学JAVAtring 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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜