简体   繁体   中英

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

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

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

Try this:

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

[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

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

if you want to send id and name as separate paramamters change your controller to

public ActionResult DoSomething(string id, string name) 
{

}

and your ajax call data to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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