AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

Create Json in Asp.Net Mvc?

I want to create like this:

[
    ['date', 'T1', 'T2', 'T3'],
    ['2000', 1, 1, 0.5],
    ['2001', 2, 0.5, 1],
    ['2002', 4, 1, 0.5],
    ['2003', 8, 0.5, 1],
    ['2004', 7, 1, 0.5]
]

from my model

public partial class AylikOkumaIstatistik
{
    public string sno { get; set; }
    public string date{ get; set; }
    public Nullable<decimal> TotalUsageValue { get; set; }
    public string UsageType { get; set; } // T1,T2,T3
}

This is possible with using json? If it is possible, is there any code example or tutorial about this topic.How can I convert data that is from database to json?

Thanks.

Upvotes: 1

Views: 3264

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

This is possible with using json?

Of course, you could use the object[] type as view model (where each element is itself an object[]):

public ActionResult Index()
{
    object[] model = new[]
    {
        new object[] { "date", "T1", "T2", "T3" },
        new object[] { "2000", 1, 1, 0.5 },
        new object[] { "2001", 2, 0.5, 1 },
        new object[] { "2002", 4, 1, 0.5 },
        new object[] { "2003", 8, 0.5, 1 },
        new object[] { "2004", 7, 1, 0.5 },
    };
    return Json(model, JsonRequestBehavior.AllowGet);
}

As far as converting the data that is in your database to this view model is concerned, well, you will have to give an example of how is your data represented in the database. Ideally provide a hardcoded example of how your model will look like. But it will be a simple matter of projecting your domain model to an object[].

Upvotes: 1

Denis Agarev
Denis Agarev

Reputation: 1529

If you can use Mvc 4? you can add WebApi controller to manage json requests. You will need just to return your entity in WepApi controller method and it will be automatically converted into json object and vice versa. It will work even if you have json objects in post requests body, they will also map to you .net entities and come into controller method as incoming params. If you need i can give any examples you need.

Upvotes: 1

Related Questions