【问题标题】:After getting the search value by Ajax, redirect to result another View通过ajax获取搜索值后,重定向到result另一个View
【发布时间】:2017-07-06 07:13:13
【问题描述】:

参数search来自Ajax post的Index视图。在搜索过程之后,我想将 employees 对象发送到 Result 视图。结果操作和视图位于同一控制器和同一视图文件夹中。但 RedirectToAction(employees) 不受影响。通过 Ajax 从视图中获取搜索值或从数据库中获取相应的员工都没有问题,都可以。 This post 说您不能从 Ajax 帖子重定向。我不知道如何将员工对象重定向并发送到结果视图。我不想通过 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);
            }
        });
    });
});

【问题讨论】:

  • 所以帖子还说,您可以通过将重定向 URL 值分配给 window.location.href 来从 javascript 重定向(您可以在 success 回调中执行此操作)。
  • @Set 但是我怎样才能通过重定向发送员工?
  • 好吧,我的错,这只有在你可以使用查询参数的情况下才有帮助。对于 POST 数据,您可以构造并填写隐藏的method=POST action="http://redirect_url" form 并提交。查看Send POST data on redirect with Javascript/jQuery
  • 我想通过 .NET MVC 方式处理这个问题。你知道其他方法吗?
  • @JamesP 是的,你说得对,我可以通过 TempData、ViewBag 等方式完成,但我想以更专业的方式处理(如果有这样的方式)。

标签: asp.net ajax asp.net-mvc asp.net-core asp.net-core-mvc


【解决方案1】:

我创建了一个 Result 视图而不是尝试重定向到 Index 视图,从 Result 操作中删除了 HttpPost 和 FromBody 属性,将“return RedirectToAction("Index", employees)”更改为“return View(employee)”

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

【讨论】:

  • 您认为这是一种理想的方法吗?
猜你喜欢
  • 2011-03-20
  • 2019-09-25
  • 2022-01-27
  • 2022-07-05
  • 2022-11-21
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多