简体   繁体   English

如何在ASP.NET MVC中从POST接收数据

[英]How receive data from POST in asp.net MVC

I have a problem trying to receive data from POST and return again in a list, this for probate what WORK 我在尝试从POST接收数据并在列表中再次返回时遇到问题,这可以证明工作原理

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

When your are posting data to method in C# you need to have class defined with same parameters in your post method. 将数据发布到C#中的方法时,您需要在post方法中使用相同的参数定义类。

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 同样,在您的情况下Person类将像

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. 因此,正如在注释中提到的那样,以完全可选的方式创建class Person ,您可以按照最佳实践跳过它。 In that case your post method will look like 在这种情况下,您的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);
}   

It's work. 是工作。 I like use function Person(ID, name, lastname) { var person = { ID: ID, name: name, lastname: lastname }; 我喜欢使用功能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 () {

});

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM