Asp.net-Mvc

從 Razor View 接收 POST 請求時,為什麼我得到 null 而不是空字元串?

  • September 4, 2010

當沒有值時,我曾經收到空字元串:

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

所以我必須使用?? ""運算符。

為什麼會這樣?

您可以DisplayFormat在模型類的屬性上使用該屬性:

[DisplayFormat(ConvertEmptyStringToNull = false)]

引用自:https://stackoverflow.com/questions/3641723