Pass a parameter to a controller using jquery ajax

2019-01-09 10:24发布

问题:

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

   <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.

What have I done wrong?

回答1:

<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:

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


回答2:

The Way is here.

If you want specify

dataType: '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'

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'

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


回答3:

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;

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

       $("#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.