I have an action that returns json result, but some of the attributes are null and I want to convert them to empty strings instead. I heard I can use DefaultValue("")
, but it's still returning null
instead of empty string.
The action is:
[HttpGet]
public ActionResult GetResults(string date)
{
var data= GetData(); // returns List<Foo>
var json = Json(data, JsonRequestBehavior.AllowGet);
return json;
}
The Foo
class is:
public class Foo
{
public string Bar1;
[DefaultValue("")]
public int? Bar2;
}
you can't set a nullable int
to default val of ""
Try
[DefaultValue(0)]
public int? Bar2;
Like @Dave A noticed you can not assign string value to the int value.
However one thing that I wanted to warn it, have you set properly the property DefaultValueHandling
? Check it here: Removing Default Values in JSON with the MVC4 Web API
Besides that I would recommend to you that you do a string property that represent this Bar2 int property and you "Ignore" it for serialization, like:
[JsonIgnore]
[DefaultValue(0)]
public int? Bar2Int;
public string Bar2
{
return { Bar2Int.HasValue ? this.Bar2Int.Value.ToString() : String.Empty; }
}
Even better with this approach you do not need any default values attributes.
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.