Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC razor graph using jquery ajax call

I am trying to bind data to graph through razor. I pull data through a jquery ajax call and planning to bind the resultant data to graph. Is there any option to include razor code inside jquery success function? How can I bind count values to x,yValues in chart code?

https://www.asp.net/web-pages/overview/data/7-displaying-data-in-a-chart

@{
    var CountsPath = Server.MapPath("~/Content/Images/counts.jpg");

    if (File.Exists(CountsPath))
    {
        File.Delete(CountsPath);
    }

    var PathName = "~/Content/Images/counts.jpg";
    if (!File.Exists(Server.MapPath(PathName)))
    {
        var chartImage = new Chart(600, 400);
        chartImage.AddTitle("Count");
        chartImage.AddSeries(
            chartType: "Pie",
                name: "Sales",
                axisLabel: "Count",
                xValue: new[] { "2011", "2014" },//need from json
                yValues: new[] { "40", "285" });//need from json
        chartImage.Save(path: PathName);
    }
}

Jquery script

<script>
    $(document).ready(function () {
        $.ajax({
            type: 'get',
            url: '/Home/GetSales',
            success: function (data) {
//Bind sales data counts by year result to graph

            },
            error: function (response) {
                alert(response.Message);
            },
            dataType: 'json'
        });
    });
</script>

Result Json:

{"Sales":[
    {"Year":"2011", "loc":"ca"},
    {"Year":"2014", "loc":"wa"},
    {"Year":"2011", "loc":"wi"}
]}

Edit: Or Can I use jquery result groupd by inside Razor code?

like image 555
Kurkula Avatar asked Jan 06 '23 00:01

Kurkula


1 Answers

As @Stephen Muecke said, this kind of solution is not possible, but, perhaps, you can try it by using a partial view to render your graph in the server and then, inject it with ajax in your web page.

Something like this:

<div>
    your page content
    <div id="graph">
    </div>
</div>

script:

$("#graph").load("MyAction", { yourdata }, function() { yourcallback });

And in "MyAction":

public ActionResult MyAction( ... ) {
    ...
    return PartialView(Model);
};

So, in this case, in 'MyAction' partial view, you can generate your graph.

like image 76
Tistkle Avatar answered Jan 07 '23 12:01

Tistkle