我正在将一个对象从客户端传递到服务器。表示为 string.empty 的对象的属性在此过程中被转换为 null。我想知道当对象类型支持 string.empty 时如何防止这种情况。
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);
}
});
我的模型包含可为 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/