ModelBinding asp.net MVC列表

时间:2011-05-23 20:48:04

标签: asp.net asp.net-mvc asp.net-mvc-3

我有以下课程:

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

如何绑定标签属性?简单的输入文本,以逗号分隔。但只有控制器我才能编码,不适用于孔应用。 感谢

1 个答案:

答案 0 :(得分:2)

您可以从编写自定义模型绑定器开始:

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);
    }
}

然后将其应用于应该接收输入的特定控制器操作:

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

现在,当您发送以下GET请求时:

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

带有HTML <form>的POST请求:

@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" />
}

Movie模型应该在控制器操作中正确绑定,并且只能在此控制器操作中绑定。

相关问题