3

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

2 Answers 2

4

you can't set a nullable int to default val of ""

Try

[DefaultValue(0)]
public int? Bar2;
Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

very interesting implementation. I'll study and make use of it.
@Dave A: Tnx! I hope you will find it useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.