从 Razor View 接收 POST 请求时,为什么我得到 null 而不是空字符串? [英] Why do I get null instead of empty string when receiving POST request in from Razor View?

查看:19
本文介绍了从 Razor View 接收 POST 请求时,为什么我得到 null 而不是空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经在没有值时收到空字符串:

I used to receive empty string when there was no value:

[HttpPost]
public ActionResult Add(string text)
{
    // text is "" when there's no value provided by user
}

但现在我正在传递一个模型

But now I'm passing a model

[HttpPost]
public ActionResult Add(SomeModel Model)
{
    // model.Text is null when there's no value provided by user
}

所以我必须使用 ??"" 运算符.

So I have to use the ?? "" operator.

为什么会这样?

推荐答案

您可以使用 DisplayFormat 模型类属性上的属性:

You can use the DisplayFormat attribute on the property of your model class:

[DisplayFormat(ConvertEmptyStringToNull = false)]

这篇关于从 Razor View 接收 POST 请求时,为什么我得到 null 而不是空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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