如何从asp.net MVC中的POST接收数据

时间:2015-07-20 03:58:43

标签: c# jquery asp.net asp.net-mvc

我在尝试从POST接收数据并在列表中再次返回时遇到问题,这是为了探究什么工作

这是我的代码:

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 () {

    });
}

控制器

[HttpPost]
public ActionResult save()
{
    // I NEED YOU - get all data here and return
    string name = Request["name"].ToString();
    return Json(name, JsonRequestBehavior.AllowGet);
}

2 个答案:

答案 0 :(得分:5)

当您在C#中向方法发布数据时,您需要在post方法中使用相同的参数定义类。

在您的情况下,您的方法将成为

[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);
}

现在,班级人员将代表您从客户处发送的内容。 再次在你的情况下,Person类就像

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

正如在完全可选中创建class Person的评论中所提到的那样,您可以跳过它仅仅是最佳实践。在这种情况下,您的post方法将类似于

[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);
}   

答案 1 :(得分:1)

它的工作。我喜欢用 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 () {

});

}