[英]How to pass a list as a parameter to a controller in MVC C#
我有一個綁定到我的視圖的列表,我還有一個 URL Action 重定向,我想在該列表中接收它並將其作為參數傳遞給我的控制器。 當調用 URL 操作時,我可以看到列表不為空,但是當它到達控制器時,列表的值為空
我的看法
<table class="table table-bordered">
<thead>
<tr>
<th>SearchTerm</th>
<th>SelectedSearchCondition</th>
<th>SelectedFieldToSearch</th>
</tr>
</thead>
<tbody>
@foreach (var item in ListOfConditions)
{
<tr>
<td>@item.SearchTerm</td>
<td>@item.SelectedSearchCondition</td>
<td>@item.SelectedFieldToSearch</td>
</tr>
}
</tbody>
</table>
}
<script type="text/javascript">
$(document).ready(function () {
$('#loadSearchResults').on('click', loadFilteredSearchResults)
});
function loadFilteredSearchResults() {
//alert('I have been clicked')
window.location.href = '@Url.Action("DisplayFilteredSearchResults", "FilteredSearch",ListOfConditions)';
}
</script>
**我的控制器方法**
public ActionResult DisplayFilteredSearchResults(List<string>ListOfConditions)
{
ListOfConditions.Count();
//ListOfConditions.Add(searchInfo);
//var model = ListOfConditions.Where(x => x.SelectedFieldToSearch.Equals(SelectFieldToSearch) && x.SelectedSearchCondition.Equals(SelectedSearchCondition) && x.SearchTerm.Equals(SearchTerm));
return View(new AdvancedSearchModel());
}
試試這個: '@Url.Action("DisplayFilteredSearchResults", "FilteredSearch", new { ListOfConditions })'
,Url.Action需要使用一個對象,該對象具有名為ListOfConditions
的屬性。 https://docs.microsoft.com/zh-cn/dotnet/api/system.web.mvc.urlhelper.action?view=aspnet-mvc-5.2#System_Web_Mvc_UrlHelper_Action_System_String_System_String_System_Object_
我想建議Url.Action
的替代方法。 原因是因為我盡可能避免混合 Razor 和 javacript 代碼,因為它們不屬於一起。 您還可以獲得不需要使用內聯 javascript 的好處,這是另一個不好的做法。 您想要做的是即時生成 GET 請求,因此我的方法是使用 GET 方法創建表單。 這是它的外觀。
$(document).ready(function () {
$('#loadSearchResults').on('click', loadFilteredSearchResults)
});
function loadFilteredSearchResults(e) {
e.preventDefault();
var conditionCount = ListOfConditions.length;
var form = document.createElement("form");
form.method = "get";
form.action = '/FilteredSearch/DisplayFilteredSearchResults';
for (var i = 0; i < conditionCount; i++) {
var input = document.createElement('input');
input.setAttribute("type", "hidden");
input.setAttribute("value", ListOfConditions[i]);
input.setAttribute("name", "ListOfConditions");
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}
如您所見,我們創建表單、設置方法、設置操作,然后將 ListOfConditions 數據添加到表單中,然后提交。 然后,瀏覽器通過提交一個帶有所需查詢字符串的 url 來為我們完成工作,控制器隨后會選擇這些查詢字符串並使用標准模型綁定來填充您的List<string> ListOfConditions
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.