Url.Action: How to Pass Parameter from View to Controller?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 03:59:30

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/26746544/url-action-how-to-pass-parameter-from-view-to-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!