Thomas
Thomas

Reputation: 34188

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

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

Upvotes: 5

Views: 8671

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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

Upvotes: 7

Scorpion-Prince
Scorpion-Prince

Reputation: 3634

Here are some answers to your questions:

  1. how many type of controller method exist in mvc - not sure what you mean by this. The methods in the controller which can be accessed through a routed URL are called Controller Action methods. These methods are mapped using the RouteConfig class in the Global.asax file of the ASP.net MVC application.
  2. url: "/Portfolios/getTradeContribs", what kind of url it is - These are restful URLs. The MVC framework maps these URLs to specific methods (Controller Actions) inside a controller. Look at the asp.net mvc site for the basics of MVC.
  3. getTradeContribs is not returning ActionResult why - It is not necessary to return an ActionResult from a Controller action. There are some actionresults which are provided by the MVC framework - eg. ViewResult (to display a View), JsonResult (which gives back a JSON object) etc. In this case, you can return a string or a JsonResult. By returing a string, the client side script needs to parse it into a JSON object, if you return a JsonResult, the client script would have a populated JSON object to work with.
  4. what is the significiant of ActionResult - ActionResult is an abstract base class, which translates the results of the Controller Action into various formats (HTML, JSON, XML etc.). it is just an easy way to render the results of the controller actions, or in your case to pass the results back to the client.
  5. why id is passing as query string and rest of the data as json. how it will works - The ASP.Net MVC framework has a component called Model Binder which when invoking the action method will try to bind the values passed in through the query string and the form post values and bind it to the parameters in the method. You can plug-in your own Modelbinder if you wanted to change the logic used to bind the values to the parameter.

Hope these answer your question. However, before you start playing with a technology, you should learn the basics of that technology / framework. Please do not treat this forum as a replacement for learning the basic. For this reason, I'm downmarking your question.

Upvotes: 2

Related Questions