【问题标题】:Pass a parameter to a controller using jquery ajax使用 jquery ajax 将参数传递给控制器
【发布时间】:2011-02-12 11:46:17
【问题描述】:

我已经创建了一个视图和一个控制器,我想要返回一些搜索结果的控制器。我正在使用 jquery 调用控制器

   <input type="text" id="caption" />
        <a href="#" id="search">Search</a>
        <script>
            $("#search").click(function () {
                alert('called');
                var p = { Data: $('#search').val() };
                $.ajax({
                    url: '/Ingredients/Search',
                    type: "POST",
                    data: JSON.stringify(p),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        alert(data);
                    },
                    error: function () {
                        alert("error");
                    }
                });
            });

我的控制器是这样的

 [HttpPost]
    public ActionResult Search(string input)
    {
        var result = _db.Ingredients.Where(i => i.IngredientName == input);

        return new JsonResult() {Data = new {name="Hello There"}};
    }

我的问题是我不确定如何从我的 jquery 调用中获取变量到控制器中,我在控制器上放置了一个断点并且它被击中但是输入字符串始终为空。

我做错了什么?

【问题讨论】:

    标签: jquery asp.net-mvc-3


    【解决方案1】:
    <input type="text" id="caption" />
    @Html.ActionLink("Search", "Search", "Ingredients", null, new { id = "search" })
    

    然后在一个单独的 javascript 文件中不显眼地 AJAXify 这个链接:

    $(function() {
        $("#search").click(function () {
            $.ajax({
                url: this.href,
                type: 'POST',
                data: { input: $('#caption').val() },
                success: function (result) {
                    alert(result.name);
                },
                error: function () {
                    alert("error");
                }
            });
            return false;
        });
    });
    

    您的控制器操作可能如下所示:

    [HttpPost]
    public ActionResult Search(string input)
    {
        var result = _db.Ingredients.Where(i => i.IngredientName == input);
        // TODO: Use the result variable in the anonymous object
        // that is sent as JSON to the client
        return Json(new { name = "Hello There" });
    }
    

    【讨论】:

    • 正确。解释一下:如果您在 C# 中的变量和您传递的 JSON 元素中使用的字段具有相同的名称,它们将自动相互绑定。因此,如果您将 JSON 属性更改为 { captionvalue: $('#caption').val() },您还必须将函数中的变量重命名为 captionvalue。只是一些解释,以便您了解为什么会这样:-)
    【解决方案2】:

    路就在这里。

    如果你想指定

    数据类型:'json'

    然后使用,

    $('#ddlIssueType').change(function () {
    
    
                var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };
    
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
                    data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
                    dataType: 'json',
                    cache: false,
                    success: function (data) {
                        $('#ddlStoreLocation').get(0).options.length = 0;
                        $('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');
    
                        $.map(data, function (item) {
                            $('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
                        });
                    },
                    error: function () {
                        alert("Connection Failed. Please Try Again");
                    }
                });
    

    如果不指定

    数据类型:'json'

    然后使用

    $('#ddlItemType').change(function () {
    
            $.ajax({
                type: 'POST',
                url: '@Url.Action("IssueTypeList", "SalesDept")',
                data: { itemTypeId: this.value },
                cache: false,
                success: function (data) {
                    $('#ddlIssueType').get(0).options.length = 0;
                    $('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');
    
                    $.map(data, function (item) {
                        $('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
                    });
                },
                error: function () {
                    alert("Connection Failed. Please Try Again");
                }
            });
    

    如果你想指定

    dataType: 'json' 和 内容类型:'应用程序/json;字符集=utf-8'

    然后使用

    $.ajax({
                type: 'POST',
                url: '@Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
                data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                cache: false,
                success: function (data) {
    
                    $('#ddlAvailAbleItemSerials').get(0).options.length = 0;
                    $('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');
    
                    $.map(data, function (item) {
                        $('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
                    });
                },
                error: function () {
                    alert("Connection Failed. Please Try Again.");
                }
            });
    

    【讨论】:

      【解决方案3】:

      问题是为了让 DefaultModelBinder 工作,它需要按名称匹配参数。您可以将您的操作参数的名称更改为默认路由中的“id”名称,默认为“id”,然后执行此操作;

              $("#search").click(function () {
                  alert('called');
                  var url = '/Ingredients/Search/' + $('#search').val();
                  $.ajax({
                      url: url,
                      type: "POST",
                      dataType: "json",
                      contentType: "application/json; charset=utf-8",
                      success: function (data) {
                          alert(data);
                      },
                      error: function () {
                          alert("error");
                      }
                  });
              });
      

      或者,您可以自己编写 Json 字符串以在服务器端匹配的方式构造它;

             $("#search").click(function () {
                  alert('called');
                  var p = { "input": $('#search').val() };
                  $.ajax({
                      url: '/Ingredients/Search',
                      type: "POST",
                      data: p,
                      dataType: "json",
                      contentType: "application/json; charset=utf-8",
                      success: function (data) {
                          alert(data);
                      },
                      error: function () {
                          alert("error");
                      }
                  });
              });
      

      这是未经测试的,但应该可以工作。

      【讨论】:

      • 嗨大卫,我试过了,但是没有任何运气。我更新了控制器参数,但它仍然返回为空。还有其他建议吗?
      • 抱歉,我刚刚意识到我使用的是搜索超链接中的值,而不是标题文本框。所以尝试用 $("caption").val() 替换 $("search").val() 行
      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 2020-05-09
      • 2020-11-09
      • 2016-03-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多