ASP.NET mvc 3模型绑定字符串列表

时间:2014-04-11 04:52:01

标签: asp.net-mvc model-binding

我目前正在使用模型绑定和ASP.NET MVC 3和.NET 4.0。

  1. 查看模型类:

    public class BasicViewModel 
    {
        [Display(Name = @"Names")]
        [Required(ErrorMessage = @"Names is required")]
        [DisplayFormat(ConvertEmptyStringToNull = true)]
        List<string> Names { get; set; }
    
        [Display(Name = @"Email")]
        [Required(ErrorMessage = @"Email is required")]
        string Email { get; set; }
    
    }
    
  2. 控制器

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult NameEmail( BasicViewModel basicModel)
    {
          // some manipulation of data
    }
    
  3. 在cshtml文件(razor视图引擎)中查看

     // model declared here using @model BasivViewModel
     // only required part shown labels part of code removed
     @Html.TextBoxFor(model => model.Names)
     ...
     @Html.TextBoxFor(model => model.Email)
     ...
    
  4. ASP.NET MVC提供的模型绑定将字符串Email绑定为null,如果它为空但将List Names绑定为空字符串(&#34;&#34;)。我希望它为null。我通过单击提交按钮解析表单字段的值,使用JavaScript进行绑定工作。但是我想要asp.net模型绑定来做到这一点。此外,如果Data Annotations类中的某些字段对此功能而言是必需的,那将会很棒。我试过这个Null Display Text Property并参考备注部分。有没有解决方案,或者这是如何实现的?我不确定我是否正确理解了这部分模型绑定。

1 个答案:

答案 0 :(得分:0)

默认情况下,如果表示数组的字段位于html中,则控制器将接收长度为0的数组。但是,要使数组为null,可以定义自定义的ModelBinder。

public class MyModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(List<string>))
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;
            // Check to see if any of the elements the array is not empty and
            // returns null if they all are.
            return request.Form.GetValues("Names").Any(x => !string.IsNullOrWhiteSpace(x)) ?
                base.BindModel(controllerContext, bindingContext) :
                null;
            //You can also remove empty element from the array as well, by using
            // a where clause
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

或者,您也可以实现IModelBinder而不是DefaultModelBinder。

下一步是在Global.asax.cs文件的Application_Start函数中注册自定义绑定器。

ModelBinders.Binders.Add(typeof(List<string>), new MyModelBinder());

这基本上告诉mvc引擎在字段MyModelBinder时使用List<string>

了解更多关于modelbinder,goolge&#34; MVC自定义模型绑定&#34;。让我知道你去:))