0

I would like to have an auto-save for the forms on some of my website's pages. So I hook into window.onbeforeunload to submit forms. My issue is that I'd like to give them a success or error message with toastr but I don't know if something already exists to persist the data from one controller action to any action on the site. I don't think I will be able to use redirects with tempdata or the viewbag. Does this functionality exist already?

David Carek
  • 1,103
  • 1
  • 12
  • 26

3 Answers3

1

Have you tried to look into Action Filters, you can capture the Action Result in the Action Filter and Save the data. Also you can apply action filters selectively to Actions or Globally. Have a look here - http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs

Preet Singh
  • 1,791
  • 13
  • 16
0

Why don't you use models? I think the best way to pass data through controllers is just passing the model you submit to respective actions like

return View("ViewName",model);

Or use RedirectToAction if you have to acess another controller

return RedirectToAction("YourAction", "YourController", new {model = yourModel});

To toastr I recommend create a wrapper, see http://labs.bjfocus.co.uk/2014/06/create-an-mvc-wrapper-for-toastr/

Antonio Correia
  • 1,093
  • 1
  • 15
  • 22
  • I am allowing the user to go to any page so I can't use the redirect without adding some way of posting the redirect location with the rest of the data. – David Carek Jul 15 '16 at 13:47
0

So I was able to get this to work by using OnActionExecuting similar to Preet Singh's response but with some additional pieces.

    public const string SESSION_ERROR = "SessionError";
    public const string SESSION_SUCCESS = "SessionSuccess";

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);
        ViewBag.Error = HttpContext.Session[SESSION_ERROR];
        ViewBag.Success = HttpContext.Session[SESSION_SUCCESS];
        HttpContext.Session[SESSION_ERROR] = string.Empty;
        HttpContext.Session[SESSION_SUCCESS] = string.Empty;
    }

The code above is used to persist the messages to any controller action and allows me to set the messages easily with the HttpContext.Session. This code is in a BaseController and all controllers extend it.

Community
  • 1
  • 1
David Carek
  • 1,103
  • 1
  • 12
  • 26