【问题标题】:MVC JsonResult Method not accepting parameterMVC JsonResult 方法不接受参数
【发布时间】:2010-05-10 15:52:29
【问题描述】:

我有一个接受一个字符串参数的 MVC JsonResult 方法:

    public JsonResult GetDestinations(string countryId)
    {
        List<Destination> destinations = new List<Destination>();

        string destinationsXml = SharedMethods.GetDestinations();
        XDocument xmlDoc = XDocument.Parse(destinationsXml);
        var d = from country in xmlDoc.Descendants("Country")
                from destinationsx in country.Elements("Destinations")
                from destination in destinationsx.Elements("Destination")
                where (string)country.Attribute("ID") == countryId
                select new Destination
                {
                    Name = destination.Attribute("Name").Value,
                    ID = destination.Attribute("ID").Value,
                };
        destinations = d.ToList();

        return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
    }

用jquery方法调用方法:

        //Fetch Destinations
        $("#Country").change(function () {
            var countryId = $("#Country > option:selected").attr("value");
            $("#Destination").html("");
            $("#Resort").html("");
            $("#Resort").append($("<option></option>").val(0).html("---Select---"));
            $.ajax({
                type: "POST",
                traditional: true,                    
                url: "/Destinations/GetDestinations",
                data: "{countryId:'" + countryId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    BindDestinationSelect(msg)
                }
            });
        });

但是,JsonResult 似乎只接收一个空参数。即使 Firebug 显示正在传递参数:

JSON 国家标识 “11” 资源 {countryId:'11'}

有什么想法吗?谢谢

【问题讨论】:

  • FWIW,"{countryId:'" + countryId + "'}" 不是 JSON。 JSON 需要双引号。你真的应该使用类似json.org/json2.js 的东西将对象序列化为 JSON 格式

标签: c# asp.net-mvc json


【解决方案1】:

我认为问题在于你实际上是如何传递数据的,你是作为一个字符串这样做的:

data: "{countryId:'" + countryId + "'}",

实际上,您应该在客户端使用结构;

data: { countryId: countryId },

jQuery 应该能够正确处理传递 id。正如您现在所做的那样,它正在尝试将 JSON 发送到服务器,这不是 MVC 所期望的,它需要一个带有名称/值对的 POST。

您可能还想考虑jQuery Form Plugin,因为它使您的 Javascript 结构序列化为 POST 数据非常容易。

【讨论】:

  • 当我在 Firebug 中查看 POST 请求时,它正在传递一个名称/值对。当我调用 web 服务(而不是调用 MVC 方法)时,这种传递参数的方式完全相同
【解决方案2】:

啊,经过一番搜索,我终于找到了失败的原因。

与格式错误的 JSON 等无关,而是控制器方法不知道如果您尝试向其传递 JSON 值会发生什么:

http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=863

所以在我的例子中,我只是选择将单个字符串值传递给它。

        $("#Country").change(function () {
            var countryId = $("#Country > option:selected").attr("value");
            $("#Destination").html("");
            $("#Resort").html("");
            $("#Resort").append($("<option></option>").val(0).html("---Select---"));
            $.ajax({
                type: "POST",
                traditional: true,
                url: "/Destinations/GetDestinations",
                data: "countryId=" + countryId,
                success: function (msg) {
                    BindDestinationSelect(msg.Data)
                }
            });

【讨论】:

    【解决方案3】:

    这里我建议你用 HttpPost 属性来装饰你的动作 喜欢:-

    [HttpPost]
    public JsonResult GetDestinations(string countryId)
    {
        List<Destination> destinations = new List<Destination>();
    
        string destinationsXml = SharedMethods.GetDestinations();
        XDocument xmlDoc = XDocument.Parse(destinationsXml);
        var d = from country in xmlDoc.Descendants("Country")
                from destinationsx in country.Elements("Destinations")
                from destination in destinationsx.Elements("Destination")
                where (string)country.Attribute("ID") == countryId
                select new Destination
                {
                    Name = destination.Attribute("Name").Value,
                    ID = destination.Attribute("ID").Value,
                };
        destinations = d.ToList();
    
        return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
    }
    

    【讨论】:

      【解决方案4】:
      public JsonResult BindAllData(string Userid)
          {
      
              List<VoteList> list = new List<VoteList>();
              var indexlist = db.TB_WebSites.ToList();
              int i = 0;
              var countlist = db.Tb_Votes.ToList();
              var VCountList = db.Tb_Votes.ToList();
              foreach (TB_WebSites vt in indexlist)
              {
                  bool voted = false;
              }
      
              return Json(new { List = _list });
      
          }
      
      
          function DataBind() {
              $("#LoadingDatas").show();
              var userid = $("#FBUserId").text();
              //alert('Data : ' + userid);
              var InnerHtml = "";
              $.ajax(
                  {
                      url: '/Gitex/BindAllData/',
                      type: 'POST',
                      data: { "Userid": userid },
                      dataType: 'json',
                      async: true,
                      success: function (data) {
                          //alert('Done');
                          //alert(data.List.length);
                          for (var i = 0; i < data.List.length; i++) {
      
                  });
      
          }
      

      试试这个,它对我有用 jQuery函数 成功:函数(目的地)

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-01
        • 1970-01-01
        • 2012-03-18
        • 1970-01-01
        • 2010-09-19
        相关资源
        最近更新 更多