Monday, August 8, 2011

Empty string is empty string

Encountered a non-orthogonal decision ASP.NET MVC team made with regards to empty string when it is passed to a variable or passed to property/variable of an object.

Given this:

public class Person
{
    // even all these properties are non-property(i.e. field),
    // these will still receive null from empty string
    public string Lastname { get; set; }
        
    // same banana, will receive null from empty string
    // public string Lastname;

    public string Firstname { get; set; }
    public string Middlename { get; set; }
}


And these parameters:
http://localhost/Product/SaveA?Lastname=Buen&Firstname=
http://localhost/Product/SaveB?Lastname=Buen&Firstname=

This..
[HttpPost]
public void SaveA(string Lastname, string Firstname, string Middlename)
{
 return Json(new { Lastname, Firstname, Middlename }, JsonRequestBehavior.AllowGet);
}

..has this output:
{"Lastname":"Buen","Firstname":"","Middlename":null}

Do notice that Firstname's value is empty string.


And this..
[HttpPost]
public void SaveB(Person p)
{
 return Json(new { p.Lastname, p.Firstname, p.Middlename }, JsonRequestBehavior.AllowGet);
}

..has this output:
{"Lastname":"Buen","Firstname":null,"Middlename":null}

Notice the difference? The Firstname on SaveA action is empty string; on SaveB action it is null, even though we pass empty string to SaveB. Middlename on both actions is null as we didn't pass Middlename to controller


To fix that inconsistency, you need to inform ASP.NET MVC that the Person object should receive empty string from er.. empty string. Put this attribute on your model:


public class Person
{
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string Lastname { get; set; }
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string Firstname { get; set; }
    [DisplayFormat(ConvertEmptyStringToNull = false)]
    public string Middlename { get; set; }
}


Then your Lastname shall receive empty string from empty string

No comments:

Post a Comment

Post a Comment