2015-07-20 123 views
-1

接收数据我有一个问题,试图从POST接收数据,并在列表中再次回归,这对于遗嘱哪些工作如何从POST在asp.net MVC

这是我的代码:

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); 
} 
+0

你试图返回它作为JsonResult?你能调试save ActionResult吗? – Chris

+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提到,你可以跳过这只是最佳实践。在这种情况下,您的发布方法看起来像

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

你不需要“上课”,这是最佳做法,但它不是“必须” –

+0

需要将参数串联起来吗? – Chris

+0

@SantiagoHernández:同意。我只是为了更好的理解。 Chris:你的意思是ajax中的person对象需要stringify吗? – Dnyanesh

0

这是工作。我喜欢使用 函数Person(ID,姓名,姓氏) { var person = {ID:ID,name:name,lastname:lastname};

​​

}