Reputation: 23
I have a problem with my CRUD application, I have two CRUDs one for Products and other for Categories. 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. 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. I would like it to go back to the edited product eg. Products/Edit/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.
This is my ActionResult for the Categories Controller.
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>
Upvotes: 1
Views: 1901
Reputation: 2101
In .Net Core 3.1 just put this line inside your controller method will redirect to the previous page
return Redirect(HttpContext.Request.Headers["Referer"]);
That is all you need.... Check it out
Upvotes: 1