[英]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.