c# - 将 JSON 对象传递给 MVC Controller 时,string.empty 转换为 null

标签 c# javascript jquery asp.net-mvc

我正在将一个对象从客户端传递到服务器。表示为 string.empty 的对象的属性在此过程中被转换为 null。我想知道当对象类型支持 string.empty 时如何防止这种情况。

enter image description here

console.log("DataToPost:", dataToPost);

$.ajax({
    type: "POST",
    contentType: 'application/json'
    url: "../../csweb/Orders/SaveOrderDetails/",
    data: dataToPost,
    success: function (result) {
        console.log(result);
    },
    error: function (e) {
        console.error(e);
    }
});

enter image description here

我的模型包含可为 null 的 DateTime 对象。我无法在服务器上将所有空值强制为 string.empty。

我正在使用 AutoMapper,所以我不想在服务器上单独检查属性。

最佳答案

这是一个 MVC 功能,它将空字符串绑定(bind)到 null

此逻辑由 ModelMetadata.ConvertEmptyStringToNull 控制DefaultModelBinder 使用的属性。

您可以使用 DisplayFormat 属性设置 ConvertEmptyStringToNull

public class OrderDetailsModel
{
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string Comment { get; set; }

    //...
}

但是,如果您不想注释所有属性,您可以创建一个自定义模型绑定(bind)器,并将其设置为 false:

public class EmptyStringModelBinder : DefaultModelBinder 
{
    public override object BindModel(ControllerContext controllerContext,
                                     ModelBindingContext bindingContext)
    {
        bindingContext.ModelMetadata.ConvertEmptyStringToNull = false;
        Binders = new ModelBinderDictionary() { DefaultBinder = this };
        return base.BindModel(controllerContext, bindingContext);
    }
}

并且您可以使用 ModelBinderAttribute在你的行动中:

public ActionResult SaveOrderDetails([ModelBinder(typeof(EmptyStringModelBinder))] 
       OrderDetailsModel orderDetailsModel)
{
}

或者您可以在 Global.asax 中将其全局设置为默认 ModelBinder:

ModelBinders.Binders.DefaultBinder = new EmptyStringModelBinder();

您可以阅读有关此功能的更多信息 here .

关于c# - 将 JSON 对象传递给 MVC Controller 时,string.empty 转换为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12734083/

相关文章:

javascript - 提交带有多个复选框/选择菜单的表单信息

jquery - 使用 jquery ajax 调用与 dotnetnuke

jquery - 如何对以 YYYY-M 格式字符串化的日期数组进行排序?

C# 格式化货币

javascript - 圆形路径中的位图旋转CreateJS Tweenjs

c# - 将 ScriptableObjects 加载到单个预制件/多个预制件的最佳实践是什么?

javascript - 来自客户端的 Meteor.js 和 Mongo : can you insert a new document or parameter into the user. 配置文件?

javascript - 当我将鼠标悬停在元素上时如何获取鼠标的偏移量..使用 jquery

c# - 在 WPF 中的 xaml View 中打开另一个窗口

c# - XPathResultType 定义错误?