将数据从JavaScript发送到控制器 [英] Send data from JavaScript to Controller

查看:83
本文介绍了将数据从JavaScript发送到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在Controller中看到来自JavaScript的数据,但确实在Request Header中看到了值.我不知道为什么这行不通....

I am not able to see the data from my JavaScript in my Controller but I DO see the value in my Request Header. I have no clue why this isn't working....

JavaScript

JavaScript

$('#Save').click(function (e) {
    if (document.forms[0].checkValidity()) {

    e.preventDefault();

    $.ajax({
      url: "/Home/SaveDetails",
      dataType: "json",
      data: JSON.stringify({ data: "test" }),
      type: "POST",
      contentType: "application/json;charset=utf-8",
      success: function (result) {
      if (result > 0) {
        alert("Worked!);
      } else {
        alert("There was an issue.");
      }
    },
    complete: function () {
      alert("Completed!");
    },
    error: function (jqXHR, textStatus, errorThrown) {
      // Handle error.
      alert(errorThrown);
    }
  });
 }
 else {
   alert("Form is not valid");
 }
});

控制器

[HttpPost]
public ActionResult SaveDetails(string value)
{
    return Json(true, JsonRequestBehavior.AllowGet);  
}

如果我修改上面的ajax请求的url参数,使其包含> url之类的内容:"/Home/SaveDetails?username =" +'sampleUser'我可以在控制器中看到该数据,但是无论采用哪种方式我看不到使用data参数从ajax请求发送的任何内容.

If I modify the url parameter of the ajax request above to include something like > url: "/Home/SaveDetails?username=" + 'sampleUser' I can see that data in my controller but no matter what approach I take I don't see anything sent from the ajax request using the data parameter.

推荐答案

要发送给控制器的数据的名称必须与您要匹配的参数的名称匹配.在您的情况下,您将数据命名为"data",参数称为"value".这应该解决它:

The name of the data you are sending the controller must match the name of the parameter you wish to match. In your case you are naming the data "data" and the parameter is called "value". This should fix it:

data: JSON.stringify({ value: "test" })

顺便说一句,您不需要使用JSON.stringify来发送数据.以下行同样适用:

As an aside, you don't need to use JSON.stringify for sending your data. The following line would work just as well:

data: { value: "test" },

此外,如果您的数据与类匹配,则mvc将尽其所能来匹配发送给类属性名称的数据:

Also, if your data matches a class, mvc will do its best to match the data sent to the class property names:

public class MyClass
{
    public int Quantity { get; set; }
    public string Title { get; set; }
}

public ActionResult DoStuff(MyClass myClass)
{
    //do stuff
}

然后在您的ajax中可以拥有:

Then in your ajax you could have:

data: { quantity: 32, title: 'Stuff & Things' },

,控制器会将ajax请求中的数据与您的模型匹配.

and the controller would match the data in the ajax request to your model.

这篇关于将数据从JavaScript发送到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆