使用 jquery ajax 将参数传递给控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4977858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:19:16  来源:igfitidea点击:

Pass a parameter to a controller using jquery ajax

jqueryasp.net-mvc-3

提问by Diver Dan

I have created a view and a controller, the controller I am wanting to return some search results. I am calling the controller using jquery

我已经创建了一个视图和一个控制器,我想要返回一些搜索结果的控制器。我正在使用 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");
                    }
                });
            });

My controller looks like this

我的控制器看起来像这样

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

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

My problem is I am not sure how to get the varible from my jquery call into the controller, I have put a breakpoint on the controller and its been hit however the input string is always null.

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

What have I done wrong?

我做错了什么?

回答by Darin Dimitrov

<input type="text" id="caption" />
@Html.ActionLink("Search", "Search", "Ingredients", null, new { id = "search" })

and then unobtrusively AJAXify this link in a separate javascript file:

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

$(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;
    });
});

where your controller action could look like this:

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

[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" });
}

回答by Md. Nazrul Islam

The Way is here.

道就在这里。

If you want specify

如果你想指定

dataType: 'json'

数据类型:'json'

Then use,

然后使用,

$('#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");
                }
            });

If you do not specify

如果不指定

dataType: 'json'

数据类型:'json'

Then use

然后使用

$('#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");
            }
        });

If you want specify

如果你想指定

dataType: 'json' and contentType: 'application/json; charset=utf-8'

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

Then Use

然后使用

$.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.");
            }
        });

回答by davidferguson

The problem is in order for the DefaultModelBinder to work it needs to match the parameter by name. You could change the name of your action parameter to the name of the "id" in your default route, which is "id" by default, then do this;

问题是为了让 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");
                }
            });
        });

Or, you could write the Json string yourself to construct it in a way that would be matched at server side;

或者,您可以自己编写 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");
                }
            });
        });

This is untested but should work.

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