【问题标题】:Jquery ajax not passing parameters to controller method in Asp.Net Core MVCJquery ajax 未将参数传递给 Asp.Net Core MVC 中的控制器方法
【发布时间】:2017-04-13 09:16:22
【问题描述】:

我正在使用以下代码来调用控制器方法并传递参数。 方法被调用,但控制器方法中的值变为 null。

相同的代码在 MVC 4 项目中运行良好,但在 Asp.Net Core MVC 中却无法运行。

var UserModel = {
  "FName": "Abc",
  "LName": "Pqr"
};
$.ajax({
  url: 'http://localhost:60600/Home/AddUser/',
  type: "POST",
  contentType: 'application/json; charset=utf-8',
  dataType: "json",
  data: JSON.stringify(UserModel),
  success: function () {
  }
});
public class HomeController : Controller
{
  // GET: /<controller>/
  public IActionResult Index()
  {
    return View();
  }

  // [HttpPost]
  // [AllowAnonymous]
  public IActionResult AddUser(UserModel model)
  {
    //  Add user model
    return Json("");
  }
}

public class UserModel
{
  public string FName { get; set; }
  public string LName { get; set; }
}

【问题讨论】:

  • 试试data: UserModel,

标签: jquery ajax


【解决方案1】:

你可以这样试试

var UserModel =
{
    FName: "Abc",
    LName: "Pqr"
};
$.ajax({
    url: '/Home/AddUser/',
    type: "POST",
    //contentType: 'application/json; charset=utf-8',
    dataType: "json",
    data: UserModel,
    success: function () {

    }
});

【讨论】:

    【解决方案2】:

    请移除 JSON.stringify

    var UserModel = {
      "FName": "Abc",
      "LName": "Pqr"
    };
    $.ajax({
      url: 'http://localhost:60600/Home/AddUser/',
      type: "POST",
      contentType: 'application/json; charset=utf-8',
      dataType: "json",
      data: UserModel,
      success: function () {
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      相关资源
      最近更新 更多