ModelBinding asp.net MVC名单 [英] ModelBinding asp.net MVC List

查看:68
本文介绍了ModelBinding asp.net MVC名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

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

推荐答案

您可以写一个自定义的模型绑定启动:

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
}

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

Now when you send the following GET request:

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

或使用HTML POST请求&LT;形式为GT;

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.

这篇关于ModelBinding asp.net MVC名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆