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

时间:2010-09-04 09:51:17

标签: asp.net-mvc string razor null viewmodel

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

[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
}

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

为什么会这样?

3 个答案:

答案 0 :(得分:143)

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

[DisplayFormat(ConvertEmptyStringToNull = false)]

答案 1 :(得分:8)

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

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

答案 2 :(得分:2)

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

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

        return View(entity);
    }

这称之为: -

    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, "");
            }
        }
    }

如果您使用Database First并且您的Model属性每次都被清除,或其他解决方案失败,那将非常有用。