简体   繁体   English

.Net Core MVC | 如何重定向回调用页面

[英].Net Core MVC | How to redirect back to the calling page

I have a problem with my CRUD application, I have two CRUDs one for Products and other for Categories.我的 CRUD 应用程序有问题,我有两个 CRUD,一个用于产品,另一个用于类别。 When I am editing Product I have a dropdown list with categories and an action link ( + Add Category) to redirect to the Categories controller action to add a new category.当我编辑产品时,我有一个包含类别的下拉列表和一个操作链接(+ 添加类别)以重定向到类别 controller 操作以添加新类别。 My problem is that once I click to add new category I'm redirected to another controller Categories/Create and after submitting the new category it goes to Categories/Index.我的问题是,一旦我单击添加新类别,我就会被重定向到另一个 controller 类别/创建,并在提交新类别后转到类别/索引。 I would like it to go back to the edited product eg.我想把它 go 返回到编辑过的产品,例如。 Products/Edit/5.产品/编辑/5。 I am not sure how to approach.我不知道如何接近。 I have used the JS script onClick to go back in history -1 but it's not the right solution for it.我在历史上使用了 JS 脚本 onClick 到 go -1,但这不是正确的解决方案。

This is my ActionResult for the Categories Controller.这是我对类别 Controller 的 ActionResult。

    public async Task<IActionResult> Create([Bind("Id,Name")] Category category)
    {
        var categoryList = _context.Categories.ToList();

        if (ModelState.IsValid)
        {
            foreach (var item in categoryList)
            {
                if (category.Name.Trim() == item.Name)
                {
                    ModelState.AddModelError("Name", "Already Exists!");
                    return View();
                }
            }
            _context.Add(category);
            
            await _context.SaveChangesAsync();
        }
            return RedirectToAction(nameof(Index));
    }

My View我的观点

 This is my View <form asp-action="Create"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="Name" class="control-label"></label> <input asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary"/> </div> </form>

In .Net Core 3.1 just put this line inside your controller method will redirect to the previous page.Net Core 3.1中,只需将此行放在 controller 方法中即可重定向到上一页

return Redirect(HttpContext.Request.Headers["Referer"]);

That is all you need.... Check it out这就是你所需要的......检查一下

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM