简体   繁体   中英

empty string returns null for textboxfor mvc 4

In the problem prepopulate Html.TextBoxFor in asp.net mvc 3 you can see an answer in which the following piece of code works correctly.

ViewBag.CompName = "Some Name";

Then in your view:

@Html.TextBoxFor(model =>model.Comps.CompName, new {@Value = ViewBag.CompName})

However, when the textbox gets the initial value of an empty string "", it seems to post a value of null for this textbox.

ViewBag.CompName = "";

This sends a null value instead of an empty string.

Is there any way of returning an empty string instead of null?

This is expected behavior. Try using DisplayFormat attribute.

[DisplayFormat(ConvertEmptyStringToNull=false)] on top of CompName property in your model.

See Reference

For Example:-

[DisplayFormat(ConvertEmptyStringToNull = false)]
public string CompName
{
    get { return _compName; }
    set { _compName= value; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM