参数搜索来自Ajax帖子的索引视图。在搜索过程之后,我想将员工对象发送到结果视图。结果操作和视图位于同一控制器和同一视图文件夹中。但 RedirectToAction(员工)并不会影响。从Ajax查看搜索值或从数据库中获取相应的员工没有问题,所有这些都很好。 This post表示您无法从Ajax帖子重定向。我不知道如何重定向&将employees对象发送到Result视图。我不想通过ViewBag来制作它。
[HttpPost]
public async Task<IActionResult> Result([FromBody]string search)
{
if (string.IsNullOrEmpty(search))
{
return NotFound();
}
IEnumerable<Employee> employees = await _context.Employees.Where(e => e.Surname == search).ToListAsync();
return RedirectToAction("Index", employees);
}
$(document).ready(function () {
$('.SearchButton').on('click', function (e) {
e.preventDefault();
var searchVal = $('.Search').val();
console.log(searchVal);
$.ajax(
{
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '@Url.Action("Index", "Employee")',
data: JSON.stringify(searchVal),
dataType: 'json',
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response.message);
}
});
});
});
答案 0 :(得分:0)
我创建了一个Result视图而不是尝试重定向到Index视图,从Result操作中删除了HttpPost和FromBody属性,更改了&#34;返回RedirectToAction(&#34; Index&#34;,员工)&#34 ;到&#34;返回查看(员工)&#34;
public async Task<IActionResult> Result(string search)
{
if (string.IsNullOrEmpty(search))
{
return NotFound();
}
IEnumerable<Employee> employees = await _context.Employees.Where(e => e.Surname == search).ToListAsync();
return View(employees);
}
<input type="text" class="Search" placeholder="Search by surname" /><a class="SearchButton">Search</a>
然后删除整个jQuery代码并替换为以下代码行:
$(document).ready(function () {
$('.SearchButton').on('click', function (e) {
window.location.href = '@Url.Action("Result")' + '/?search=' + $('.Search').val();
});
});