views:

82

answers:

3

I am using ASP.NET MVC2 for my project. I want to send the user confirmation messages after actions.

Ideally: User clicks on a link with a query string (i.e. a link to delete an entry) The controller does what the link says, creates the success message, and uses RedirectToAction to get rid of the query string from the URL. The new action displays the success message.

It was suggested I use a model error to do this, however I do not think that will work in this situation.

Thanks.

+7  A: 

You could use TempData:

public ActionResult Index()
{
    string message = TempData["message"] as string ?? string.Empty;
    // send the message as model so that the view can print it out
    return View("index", message);
}

[HttpPost]
public ActionResult DoWork()
{
    // do some work
    TempData["message"] = "Work done!";
    return RedirectToAction("index");
}

Internally TempData uses session in order to persist the information but it is automatically purged after the next request, so it will be available only on the next request following the storage.

Darin Dimitrov
+2  A: 

First of all DON'T USE GET REQUESTS TO MODIFY DATA! Imagine a search engine indexing your site and visiting all of the delete links.

Second, why can't the target action return a view to show the success/failure message?

joshperry
Is this really that bad? You must be logged in to visit the area, and the user must be the owner of what is being deleted.I've used this for a while and haven't had troubles but now you're making me wonder lol. I still have a lot to learn.
smdrager
Yes it is bad, it is even catastrophic. There are plugins that people tend to install on their browsers. Those plugins pretend to `improve the surfing experience` by indexing content the user is navigating. So no need to be a search engine. It could be the user himself without him knowing.
Darin Dimitrov
Wow. I've been using this for a while. Haha.. heh... ah crap. So instead the accepted method would be a:<form action="..." method="post"><input type="hidden" name="id" /></form>with a submit button or link using js to submit the form?
smdrager
+2  A: 

I use TempData with a message in my Site.Master file:

  <% if (TempData["Error"] != null)
     { %>

    <div id="errorMessage">
        <%= Html.Encode(TempData["Error"]) %>
    </div>
   <% } %>

   <% if (TempData["Warning"] != null)
      { %>

    <div id="warningMessage">
        <%= Html.Encode(TempData["Warning"]) %>
    </div>
   <% } %>

In my controller I can assign a value either to TempData["Error"] or to TempData["Warning"] and have them styled differently.

Carles