Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass json object from Javascript to asp.net mvc controller

Tags:

asp.net-mvc

i just started MVC so have lot of confusion. whenever we call any server side function by jquery in asp.net webform project then that method has to be static and must be decorated by webmethod attribute. so i want to know that is the same rule applies in case of mvc.

i got a code for that but i did not test it.

client side method

function getTradeContribs(id,pfid, nodedates) {

    var data = {};
    data.portfolioId = pfid;
    data.nodedates = nodedates;

    $.ajax({
            type: "POST",
            url: "/Portfolios/getTradeContribs/"+id,
            dataType: "json",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            success: parseTradeContribs,
            error: function (error) {
                    alert("failed in opening XML file !!!");
            }
    });
   }

server side method

public string getTradeContribs(int id,string portfolioId, string nodedates)
{
    string jsonTest = @" {""nodedates"": ""date"":""01/01/2012""}";
    return jsonTest;
}

from the above code i have few question 1) how many type of controller method exist in mvc 2) url: "/Portfolios/getTradeContribs", what kind of url it is. Portfolios is controller name & getTradeContribs is action name? if no then getTradeContribs is what kind of method.

3) getTradeContribs is not returning ActionResult why 4) what is the significiant of ActionResult? 5) why id is passing as query string and rest of the data as json. how it will works?

please discuss this point because i am new in mvc

like image 750
Thomas Avatar asked Aug 06 '12 17:08

Thomas


1 Answers

whenever we call any server side function by jquery in asp.net webform project then that method has to be static and must be decorated by webmethod attribute. so i want to know that is the same rule applies in case of mvc.

No, not at all. ASP.NET MVC is a completely different pattern. In ASP.NET MVC you work with controller actions that return action results (classes derived from ActionResult). So if you want to return JSON you simply define a controller action that returns a JsonResult and passes a model to it:

public ActionResult GetTradeContribs(int id, string portfolioId, string nodedates)
{
    var model = new 
    {
        nodedates = "foo",
        date = DateTime.Now
    };
    return Json(model, JsonRequestBehavior.AllowGet);
}

or even better define view models:

public class TradeContribsRequestViewModel
{
    public int Id { get; set; }
    public string PortfolioId { get; set; }
    public string NodeDates { get; set; }
}

public class TradeContribsViewModel
{
    public string NodeDates { get; set; }
    public DateTime Date { get; set; }
}

and then:

public ActionResult GetTradeContribs(TradeContribsRequestViewModel request)
{
    var model = new TradeContribsViewModel
    {
        NodeDates = "foo",
        Date = DateTime.Now
    };
    return Json(model, JsonRequestBehavior.AllowGet);
}

ASP.NET MVC will automatically serialize the model to a JSON string and pass it to the view. Then you could invoke it using ajax:

$.ajax({
    url: '@Url.Action("GetTradeContribs", "Portfolios")',
    type: 'POST',
    data: { 
        id: 123, 
        portfolioId: 'some id', 
        nodedates: 'some node dates' 
    },
    success: function(result) {
        // You could directly use the properties of the result object here
        // like for example: alert(result.nodedates);
    }
});

You should absolutely never hardcode JSON as you did in your original getTradeContribs method. That's infrastructure plumbing that is already handled by the framework for you. All you have to care about is to define:

  • a controller action returning an ActionResult
  • a model type that the controller action will pass to the view
  • a view
like image 118
Darin Dimitrov Avatar answered Nov 15 '22 03:11

Darin Dimitrov