Reputation: 23749
In an ASP.NET MVC Core project how can I use an alternative of this custom action filter class. When I copy the following in my project's controller folder it does not recognize the following objects TempData[Key], ViewData
because it's using System.Web.Mvc namespace that is not used in ASp.NET MVC Core. I want to implement POST-REDIRECT-GET in my ASP.NET MVC Core project as described here but the author, it seems, is not using MVC Core:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace myASPCoreProject.Controllers
{
public abstract class ModelStateTransfer : ActionFilterAttribute
{
protected static readonly string Key = typeof(ModelStateTransfer).FullName;
}
public class ExportModelStateAttribute : ModelStateTransfer
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//Only export when ModelState is not valid
if (!filterContext.ModelState.IsValid)
{
//Export if we are redirecting
if ((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult))
{
filterContext.Controller.TempData[Key] = filterContext.ModelState;
}
}
base.OnActionExecuted(filterContext);
}
}
public class ImportModelStateAttribute : ModelStateTransfer
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
ModelStateDictionary modelState = filterContext.Controller.TempData[Key] as ModelStateDictionary;
if (modelState != null)
{
//Only Import if we are viewing
if (filterContext.Result is ViewResult)
{
filterContext.Controller.ViewData.ModelState.Merge(modelState);
}
else
{
//Otherwise remove it.
filterContext.Controller.TempData.Remove(Key);
}
}
base.OnActionExecuted(filterContext);
}
}
}
Upvotes: 2
Views: 4847
Reputation: 159
We can use Redirect To Action as you can read in the Microsoft's documentation RedirectToAction
Configure DI:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add the temp data provider
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
}
[HttpPost]
public IActionResult Edit(User user)
{
_userRepository.Save(user);
TempData["User"] = JsonConvert.SerializeObject(user);
return RedirectToAction("Edit", new { id = user.Id });
}
other example
[HttpPost]
public IActionResult Edit(User user)
{
_userRepository.Save(user);
return RedirectToAction(nameof(UserController.Index), "User");
}
Upvotes: 3