14

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?

Diver Dan
  • 9,953
  • 22
  • 95
  • 166

3 Answers3

20
<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" });
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    Correct. To explain: if your variable in C# and the field used in the JSON element you are passing have the same name, they will automatically bound to eachother. So if you would change the JSON property to `{ captionvalue: $('#caption').val() }`, you would also have to rename the variable in your function to `captionvalue`. Just some explanation so you understand why this works :-) – Flater Aug 29 '12 at 09:00
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.");
            }
        });
Md. Nazrul Islam
  • 2,809
  • 26
  • 31
0

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.

davidferguson
  • 760
  • 5
  • 9
  • Hi David, I tried that however without any luck. I updated the controllers paramater however its still be returned as null. Any other advise? – Diver Dan Feb 12 '11 at 12:30
  • Sorry just realised I was using the value from the search hyperlink instead of the caption text box. So try replacing the line $("search").val() with $("caption").val() – davidferguson Feb 12 '11 at 15:16