1

I have a problem trying to receive data from POST and return again in a list, this for probate what WORK

This is my code:

function Person(ID, name, lastname)
{
    var person = { ID: ID, name: name, lastname: lastname };            

    $.ajax({
        url: '/Form/save',
        type: 'post',
        data: person,
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (msg) {
        console.log('Person: '+ msg);
    }).fail(function (error) {
        console.log('ERROR: '+ error.error);
    }).always(function () {

    });
}

Controller

[HttpPost]
public ActionResult save()
{
    // I NEED YOU - get all data here and return
    string name = Request["name"].ToString();
    return Json(name, JsonRequestBehavior.AllowGet);
}
2
  • Have you tried to return it as JsonResult? Were you able to debug the save ActionResult?
    – Chris
    Jul 20, 2015 at 4:00
  • What problem are you having?
    – user3559349
    Jul 20, 2015 at 4:04

2 Answers 2

5

When your are posting data to method in C# you need to have class defined with same parameters in your post method.

In your case your method will become

[HttpPost]
public ActionResult save(Person person)
{
    //Here your need to access person object to get the data 
    string name = person.name;
    return Json(name, JsonRequestBehavior.AllowGet);
}

Now class person will be representation of what your sending from your client. Again in your case Person class will be like

class Person 
{
  public int ID {get; set;}
  public string name {get; set;}
  public string lastname {get; set;}
}

So as mentioned in comments creating class Person in completely optional and you can skip that it just on of best practice. In that case your post method will look like

[HttpPost]
public ActionResult save(Object person)
{
    //Here your need to access person object to get the data 
    string name = person.name;
    return Json(name, JsonRequestBehavior.AllowGet);
}   
3
  • you don't "need" a class, it is a best practice but it's not a "must" Jul 20, 2015 at 4:12
  • Need to Stringify the parameters?
    – Chris
    Jul 20, 2015 at 4:14
  • @SantiagoHernández: Agree. I just put that for better understanding. Chris: Do you mean person object in ajax need to stringify?
    – Dnyanesh
    Jul 20, 2015 at 4:19
1

It's work. I like use function Person(ID, name, lastname) { var person = { ID: ID, name: name, lastname: lastname };

$.ajax({
    url: '@Url.Action("Controller","Action")',
    type: 'post',
    data: person,
    contentType: "application/json; charset=utf-8",
    dataType: "json"
}).done(function (msg) {
    console.log('Person: '+ msg);
}).fail(function (error) {
    console.log('ERROR: '+ error.error);
}).always(function () {

});

}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.