MVC绑定表单数据的问题 [英] MVC binding form data problem

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

问题描述

我使用的所有字段匹配我的窗体对象。然后,我使用默认绑定来填充对象在我的动作,这样的;

I am using an object that matches all the fields in my form. I then use the default binding to populate the object in my action, like this;

public ActionResult GetDivisionData(DivisionObj FormData)

我DivisionObj初始化它的所有值在构造函数中的String.Empty。

My DivisionObj initializes all it's values to string.empty in the constructor.

的问题是,当粘结剂填充从张贴表单数据的模式,即不贴设定为在对象空任何数据,eventhough我初始化为包含空字符串的对象。

The problem is that when the binder populates the model from the posted form data, any data that is not posted is set to null in the object, eventhough I initialized the object to contain empty strings.

有没有办法来改变这种使未发表的数据将是一个空字符串。

Is there a way to change this so that unposted data will be an empty string.

推荐答案

这是DefaultModelBinder的默认行为,更具体的DataAnnotations框架。 ConvertEmptyStringToNull 默认情况下,设置为true。你可以创建自己的模型粘结剂和替换默认的模型粘合剂。

This is default behavior of the DefaultModelBinder, more specifically the DataAnnotations framework. ConvertEmptyStringToNull is by default, set to true. You can create your own model binder and replace the default model binder.

public class EmptyStringModelBaseBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;

        return base.BindModel(controllerContext, bindingContext);
    }
}

然后在全球...

Then in global...

ModelBinders.Binders.DefaultBinder = new EmptyStringModelBaseBinder();

虽然我希望他们有这个设置为默认ModelBinder的静态方法。也许在V3 :)

Though I do wish they had a static way of setting this for the default modelbinder. Maybe in v3 :)

另外,您还可以使用 [DisplayFormat(ConvertEmptyStringToNull = FALSE)] 属性来设置这对每个属性的基础。

Alternatively, You can also use the [DisplayFormat(ConvertEmptyStringToNull=false)] attribute to set this on a per-property basis.

这篇关于MVC绑定表单数据的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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