Search code examples
c#asp.net-mvcasp.net-mvc-4razorhtml.textboxfor

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?


Solution

  • 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; }
    }