silent200
silent200

Reputation:

Best way to generate Json-friendly result (.NET MVC)

I'm now using ListItem() for Json format result, but the generated Json text has an extra property called "selected = false", I know this is used for drop down list, but I want my app runs faster so I don't want this property. Do you know any other way to get the similar result?

Here is my code:

List<ListItem> list = new List<ListItem>() {
    new ListItem() { Text = "Email", Value = "Pls enter your email" },
    new ListItem() { Text = "NameFull", Value = "Pls enter your full name" },
    new ListItem() { Text = "Sex", Value = "Pls choose your sex" }
};

Upvotes: 2

Views: 597

Answers (3)

Kev
Kev

Reputation: 119806

Depending on your JSON serialiser you may or may not be able to tell the serialiser to ignore this property.

You'd be better off just creating a class that only has the fields you need. e.g.

public class MyListItem
{
    public string Text { get;set; }
    public string Value { get;set; }
}

List<MyListItem> list = new List<MyListItem>() {
    new MyListItem() { Text = "Email", Value = "Pls enter your email" },
    new MyListItem() { Text = "NameFull", Value = "Pls enter your full name" },
    new MyListItem() { Text = "Sex", Value = "Pls choose your sex" }
};

Upvotes: 2

If you're using ASP.NET MVC Beta you can serialize any object to JSON using Json function and anonymous types.

public JsonResult GetData() {
    var data = new { Text = "Email", Value = "Pls enter your email" }; 
    return Json(data);
}

Upvotes: 6

Andrew Hare
Andrew Hare

Reputation: 351516

Don't use ListItem - use a custom type that has only the properties you want.

Upvotes: 0

Related Questions