为什么从 Razor View 接收 POST 请求时得到 null 而不是空字符串?
我曾经在没有值时接收空字符串:
[HttpPost]
public ActionResult Add(string text)
{
// text is "" when there's no value provided by user
}
但现在我传递一个模型
[HttpPost]
public ActionResult Add(SomeModel Model)
{
// model.Text is null when there's no value provided by user
}
所以我必须使用 ?? “”
运算符。
为什么会发生这种情况?
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.
Why is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
You can use the
DisplayFormat
attribute on the property of your model class:默认模型绑定将为您创建一个新的 SomeModel。字符串类型的默认值为 null,因为它是引用类型,因此它被设置为 null。
这是 string.IsNullOrEmpty() 方法的用例吗?
The default model binding will create a new SomeModel for you. The default value for the string type is null since it's a reference type, so it's being set to null.
Is this a use case for the string.IsNullOrEmpty() method?
我正在“创建和编辑”中尝试此操作(我的对象称为“实体”):-
这称为:-
如果您使用数据库优先并且您的模型属性每次都会被清除,或者其他解决方案失败,这将很有用。
I am trying this in Create and Edit (my object is called 'entity'):-
Which calls this:-
It will be useful if you use Database First and your Model attributes get wiped out each time, or other solutions fail.