我正在创建一个 ASP.NET MVC 应用程序。我目前正在开发一个搜索页面,其中搜索框和结果表显示在同一页面上。为此,我使用了部分 View 和带有 View 模型的 AJAX/JSON 调用。在文本框中输入两个搜索词后,通过 ajax 传递后在 Controller 中均为 null。
代码如下:
View 模型:
public class ExampleViewModel
{
public string search { get; set; }
public string search2 { get; set; }
}
Controller :
[HttpPost]
public ActionResult Search(ExampleViewModel searchTerm)
{
var searchList = db.UserLists.Where(x => x.LastName.Contains(searchTerm.search));
return PartialView("_SearchResultsPartial", searchList);
}
索引 View 主体:
<body>
<div>
@Html.TextBoxFor(model => model.search)
@Html.TextBoxFor(model => model.search2)
<input type="submit" value="Search" onclick="return getSearchResults()"/>
</div>
<div id="search-results">
</div>
<script>
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
function getSearchResults() {
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
</script>
同样,在 Search [POST] 方法上设置断点后,ExampleViewModel 的项为空。
最佳答案
乍一看,您似乎必须检索函数范围内的值:
function getSearchResults() {
//Read these values on button click
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
否则,exViewModel
仅在页面加载时确定。
关于javascript - ajax 调用后 Viewmodel 内容为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35418161/