1

can i retrieve an json object in a asp.net mvc controller?

Here's my ajax request

// get form values
var nameValue = $("#name").val();
var ageValue = $("#age").val();

// json object
var person = {

    name: nameValue,
    age: ageValue
};


        $.ajax({
            url: '/Home/GetData',
            type: 'POST',
            data:{userObj: person},
            success: function (data, textStatus) {
                alert(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Erro :" + XMLHttpRequest.responseText + "| " + textStatus + "| " + errorThrown);
            }
        });

And here's my asp.net MVC controller method

        [HttpPost]
        public String GetData(dynamic userObj)
        {
            dynamic person = System.Web.Helpers.Json.Decode(userObj);
            return userObj.name; // It didn't work
        }

I want to retrieve this object in my controller, and use it as userObj.name, userObj.age like a json object inside C# with no need to create a C# class with same parameters to this.

Is there some way?

1 Answer 1

1

You variable person is already the object you need to send to the controller so you ajax function should be

$.ajax({
    url: '@Url.Action("GetData", "Home")', // don't hard code your url's
    type: 'POST',
    data: person, // change this
    success: function (data, textStatus) {
        alert(data);
    },

and then you controller method should be

[HttpPost]
public String GetData(Person userObj)

where Person is

public class Person
{
  public string Name { get; set; }
  pubic int Age { get; set; }
}

When you post the data, the value of userObj will be correctly bound with the values of nameValue and ageValue.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer and your tips Stephen, it works fine, but is there some way to retrieve this data with no need to create a Person class in C#?
You can use parameters for each value - public String GetData(string Name, int Age)` (but why would you want to do that?)
Like you said, it is not the best way use parameters for each value. I'm looking for some way to use an Object without have the same object in C# code. Like PHP you can receive an entire object via POST and i don't need to have the same object in PHP code, i just retrieve it and save in a variable or array. But i think it is not possible in C#

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.