Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a parameter to a controller using jquery ajax

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?

like image 958
Diver Dan Avatar asked Feb 12 '11 11:02

Diver Dan


People also ask

How do I call ActionResult from ajax?

You need to remove [HttpPost] attribute. You need to be aware of ajax parameters contentType and dataType. From the documentation: contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8'). This specifies what type of data you're sending to the server.


2 Answers

<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" });
}
like image 177
Darin Dimitrov Avatar answered Sep 20 '22 08:09

Darin Dimitrov


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.");
            }
        });
like image 38
Md. Nazrul Islam Avatar answered Sep 19 '22 08:09

Md. Nazrul Islam