asp.net-mvc 从 Razor View 接收 POST 请求时,为什么我得到 null 而不是空字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3641723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:27:40  来源:igfitidea点击:

Why do I get null instead of empty string when receiving POST request in from Razor View?

asp.net-mvcstringrazornullviewmodel

提问by Alex

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?

为什么会这样?

回答by Michael Jubb

You can use the DisplayFormatattribute on the property of your model class:

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

[DisplayFormat(ConvertEmptyStringToNull = false)]

回答by hackerhasid

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.

默认模型绑定将为您创建一个新的 SomeModel。字符串类型的默认值是 null,因为它是一个引用类型,所以它被设置为 null。

Is this a use case for the string.IsNullOrEmpty() method?

这是 string.IsNullOrEmpty() 方法的用例吗?

回答by user2284063

I am trying this in Create and Edit (my object is called 'entity'):-

我正在创建和编辑中尝试此操作(我的对象称为“实体”):-

        if (ModelState.IsValid)
        {
            RemoveStringNull(entity);
            db.Entity.Add(entity);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(entity);
    }

Which calls this:-

这称为:-

    private void RemoveStringNull(object entity)
    {
        Type type = entity.GetType();
        FieldInfo[] fieldInfos = type.GetFields(BindingFlags.Instance | BindingFlags.GetField | BindingFlags.Public | BindingFlags.NonPublic);
        for (int j = 0; j < fieldInfos.Length; j++)
        {
            FieldInfo propertyInfo = fieldInfos[j];
            if (propertyInfo.FieldType.Name == "String" )
            {
                object obj = propertyInfo.GetValue(entity);
                if(obj==null)
                    propertyInfo.SetValue(entity, "");
            }
        }
    }

It will be useful if you use Database First and your Model attributes get wiped out each time, or other solutions fail.

如果您使用数据库优先并且您的模型属性每次都被清除,或者其他解决方案失败,这将非常有用。