Pass JSON to MVC 3 Action

13,959

Solution 1

I don't believe nobody saying this so I will try. Have your code like this

 public class Personal
 {
      public string Address { get; set; }
      public string City { get; set; }
      public string State { get; set; }
      //other properties here
 }

[HttpPost]
public ActionResult GetDetails(Personal address)
{         
    //Should be able to get it.            

    @ViewBag.Successs = true;

    return View();

}

In general, you can add those possible properties into the class Personal (or whatever you can name it). But according to linkedin API, you will need a tool to generate the data class due to its complexity. I think xsd.exe can help if you can get xsd file for that (or you can even generate xsd file from xml)

Solution 2

  1. Remove data: JSON.stringify(address) with data: address

  2. Action method

    [HttpPost]
    public ActionResult GetDetails(string Address, string City, string State, string PropName)
    {         
       //access variable here
    }
    

As you have said your data object may contain 20 props, to avoid creating 20 parameters, you can use formscollection like below

[HttpPost]
public ActionResult GetDetails(FormCollection address)
{        
      string city= address["city"] ;
      string anotherPro=address["prop"];          
}

Solution 3

Not sure if this will work (never done this myself), but you could try the following signature:

public ActionResult LinkedIn(dynamic address)

I'm actually quite interested myself to see what will happen then. Or, as suggested in the comment by Kristof Claes, use a FormCollection.

Second, when things like this happen, always check whether the browser actually sends the data you expected to the server. IE9 and Chrome support this out of the box, otherwise you can use a tool like Fiddler.

EDIT: Just tried for myself with a dynamic parameter and that doesn't work.. The runtime type of the parameter is object so everything you submitted is lost. You'd better use FormCollection.

Solution 4

I believe you can use a FormCollection for this.

public ActionResult LinkedIn(FormCollection address)
{
    var street = address["street"];
    ...
    return View();
}

Solution 5

My take is all the answers are sort of right.

As your don't know the number of things you're sending, use formcollection on the server. But also remove the stringfy from the ajax call. These means the data will be sent using www-encoding.

If you wnat to send n address objects, change the mvc action parameter to an array of address objects and use stringfy.

Share:
13,959

Related videos on Youtube

Eilimint
Author by

Eilimint

Updated on June 04, 2022

Comments

  • Eilimint
    Eilimint almost 2 years

    I am trying to submit JSON to a MVC action. What I want is to take the JSON object and then access it's data. The number of JSON fields will vary each time so I need a solution that will handle all cases.

    This is my POST to my action, address could have 3 fields or 20 it will vary on each post.

    Update: I'll go into a little more detail. I'm trying to use the LinkedIn API, I'll be sent a JSON which will look like the JSON at the end of this page : link. I need to create an Action which will accept this JSON which will vary for every person.

    var address =
        {
            Address: "123 rd",   
            City: "Far Away",
            State: "Over There"           
        };
    
    
        $.ajaxSetup({ cache: false });
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/Account/GetDetails/",
            data: JSON.stringify(address),
            dataType: "json",
            success: function () {
    
                alert("Success from JS");
            }
        });
    

    This is my action in MVC, I need to be apply to take whatever JSON object is passed and access its fields.

     [HttpPost]
        public ActionResult GetDetails(object address)
        {         
            //address object comes in as null            
    
            @ViewBag.Successs = true;
    
            return View();
    
        }
    
  • Ronald Wildenberg
    Ronald Wildenberg over 12 years
    But the requirement was that the number of parameters could vary from 3 to 20. Instead of using a 20-parameter action method, I'd rather use a FormCollection. You're correct when saying that it is unnecessary to transform the JSO literal to a string.
  • Eilimint
    Eilimint over 12 years
    If I use Action params it will work but if I have 20 + parameter things get messy, this will probably grow to even more in the future. Also if the JSON literals sent to me where to change then my code will fall apart.
  • Eilimint
    Eilimint over 12 years
    Sorry, was just a typo, I updated the post to reflect this. Thanks
  • Eilimint
    Eilimint over 12 years
    I'll go into a little more detail. I'm trying to use the LinkedIn API, I'll be sent a JSON which will look like the JSON at the end of this page : link. I need to create an Action which will accept this JSON which will vary for every person.
  • Eilimint
    Eilimint over 12 years
    I'll go into a little more detail. I'm trying to use the LinkedIn API, I'll be sent a JSON which will look like the JSON at the end of this page : link. I need to create an Action which will accept this JSON which will vary for every person.
  • Simon Halsey
    Simon Halsey over 12 years
  • Eilimint
    Eilimint over 12 years
    I got the FormCollection to work but only by removing the stringfy and sending the data as a string. However I won't have any control in how the data is sent. I'll just have to accept it as a JSON from LinkedIn
  • Eilimint
    Eilimint over 12 years
    My code above was just a test I was trying, here is a link to the JSON I'll be receiving link. Scroll down to see how the JSON looks. It will be send as JSON from LinkedIn so I've no control as to how I receive it. I just need to create an Action to accept it.
  • Simon Halsey
    Simon Halsey over 12 years
    when you're calling the mvc action, you've already got the response json from LinkedIn. You could send this as a string & process it on the server.
  • aruno
    aruno over 11 years
    ya I know that kinda sucks :-(
  • aruno
    aruno over 11 years
    if youre removing 'stringify' then what you're sending is NOT Json - it's just form parameters.
  • Adam Hess
    Adam Hess about 8 years
    this does not answer the question at all. You are essentially just answer the question "How do I Create a Custom Model to Bind to an Controller?"