简体   繁体   English

通过电线将数据从js发送到控制器

[英]sending data from js over wire to the controller

Inside js function I'm creating javascript object which I then send to the mvc controller using ajax 在js函数内部,我正在创建javascript对象,然后使用ajax将其发送到mvc控制器

var ab = { id: 100, name: "abc" }
$.ajax({
    type: "POST",
    url: "/home/dosomething",
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify(ab),
    success: function (result) {
        $("#myDiv").html(result);
        $("#showModal").modal("show");
    },
    error: function () {
        alert("error!");
    }
});

on server side I have 在服务器端,我有

[HttpPost]
public ActionResult DoSomething(string ab) 
{
    ... ab is always null
}

I'm guessing that I should using some other data type as expected in controller method instead of string? 我猜想我应该使用控制器方法中期望的其他一些数据类型,而不是字符串?

You need to use id and name in your action method 您需要在操作方法中使用id和name

 [HttpPost]
 public ActionResult DoSomething(int id, string name) 
 {
    //code
 }

Try this: 尝试这个:

JS: JS:

var ab = { Id: 100, Name: "abc" }
$.ajax({
        type: "POST",
        url: "/home/dosomething",
        dataType: "json",
        data: JSON.stringify({ ab: ab }),
        success: function (result) {
            $("#myDiv").html(result);
            $("#showModal").modal("show");
        },
        error: function () {
            alert("error!");
        }
    });

Controller: 控制器:

[HttpPost]
public ActionResult DoSomething(YourClass ab) 
{
  . . .
}

Model: 模型:

public class YourClass
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Make a class of the JSON object, peg it as Serializable 制作JSON对象的类,将其固定为Serializable

[Serializable]
public class SomeClass
{
    public int id { get; set; }

    public string name { get; set; }
}

In your controller, you can now accept this as: 在您的控制器中,您现在可以将其接受为:

[HttpPost]
public ActionResult DoSomething([FromBody] SomeClass someclass){
  // code
}
var ab = { id: 100, name: "abc" }
$.ajax({
    type: "POST",
    url: "/home/dosomething",
    dataType: "json",
    contentType: "application/json",
    // what if you pass data like this
    data: JSON.stringify({ab:ab}),
    success: function (result) {
        $("#myDiv").html(result);
        $("#showModal").modal("show");
    },
    error: function () {
        alert("error!");
    }
});

If you want to send { id: 100, name: "abc" } as a string to the controller you need to change the data in ajax call to 如果要将{id:100,name:“ abc”}作为字符串发送给控制器,则需要将ajax调用中的数据更改为

data: JSON.stringify({ab:ab}), 数据:JSON.stringify({ab:ab}),

if you want to send id and name as separate paramamters change your controller to 如果要发送ID和名称作为单独的参数,请将控制器更改为

public ActionResult DoSomething(string id, string name) 
{

}

and your ajax call data to 和你的ajax调用数据到

data: '{ "id":" 100 ","name":"abc" }',

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

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