Jquery – Url.Action: How to Pass Parameter from View to Controller

asp.net-ajaxasp.net-mvcasp.net-mvc-4jquery

I'm having issues with passing a parameter from my View to Controller using Url.Action.

My code is the following in the View:

<form id="searchForm">
    <input type="text" name="search_criteria" />
    <input type="submit" value="Search" />
</form>

<div id="SearchDiv">

</div>

In my Script:

$('#searchForm').submit(function (e) {
    e.preventDefault();

    $.ajax({
        url: '@Url.Action("Index_AddSearchCriteria", "Home", "search_criteria")',
        type: 'POST',
        dataType: 'html',
        success: function (result) {
            $('#SearchDiv').html(result);
        }
    })
})

In the Controller:

public PartialViewResult Index_AddSearchCriteria(string search_criteria)
        {
            ViewModel.SearchCriteria = search_criteria;

            return PartialView("SearchBar", ViewModel);
        }

How would I send a parameter through Url.Action so that it may be accepted as a parameter in the Controller?

Best Answer

You need to use the data: parameter

var data = { search_criteria: $("search_criteria).val() }; // add id="search_criteria" to the textbox
$.ajax({
    url: '@Url.Action("Index_AddSearchCriteria", "Home")',
    type: 'POST',
    data: data,
    dataType: 'html',
    success: function (result) {
        $('#SearchDiv').html(result);
    }
})

or you could simplify it to

$('#SearchDiv').load('@Url.Action("Index_AddSearchCriteria", "Home")', { search_criteria: $("search_criteria).val() });
Related Topic