Share via


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

Question

Monday, August 6, 2012 1:38 PM

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.

  1. 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

All replies (2)

Monday, August 6, 2012 2:08 PM ✅Answered

Hi,

MVC is a little easier in that respect than web forms, to answer your questions.

1) Only 1 type of controller exists

2) The controller is portfolio and the action is the method gettradecontribs, it has to be an instance method

4) Most controllers return a derivative of actionresult, it is just the base class for the results from a controller, but it could just as easily be a primitive type

5) The id is passed into the routing engine, not querystring, the routing engine takes care of putting Id into the right place in the action.  The request body is passed as a formcollection of namevalue pairs and the mvc model binder, tries to create the complex type that is mentioned in the action parameters.

If the model binder fails to bind the namevalue pairs to the complex object, you get an empty version of the complex object instead.

HTH

Si


Monday, August 6, 2012 8:07 PM ✅Answered

I think you are making it too hard on yourself, you are not letting the ModelBinder do its job by building up objects from the JSON you are passing it.  You are also not lettign the built in serializer return your objects as json.  Here is an example of an ajax call passing a Person object to the Controller and the controller returning the person object back with an additional property set.

Person Class:

   public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }
    }

Ajax call from the View:

 

   var person = {};
    person.FirstName = "John";
    person.LastName = "Doe";
    $("#btn").click(function () {
        $.ajax(
        {
            url: '@Url.Action("GetPerson", "Home")',
            data: JSON.stringify(person),
            contentType: 'application/json',
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                alert("Full Name is " + data.FullName);
            },
            error: function () { alert('error'); }
        });
    });

Notice that the object we are receiving back is json, so javascript knows how to handle it.

Here is the Action on the Controller:

   public ActionResult GetPerson(Person person)
    {
        return Json(person);
    }

First of all, we are letting the ModelBinder create a Person object out of arguements we pass from teh View.  Now we can return our defined Person object to the View as json by calling the Json()method which returns a JsonResult (which derives from ActionResult).  This method will do the serialization for you so you are not having to serialize by hand.

Hope this helps!