views:

231

answers:

2

I'm creating a messaging web app in ASP.NET and are having some problems when displaying an error message to the user if they go to send a message and there is something wrong.

A user can look through profiles of people and then click, 'send a message'. The following action is called (url is /message/create?to=username) and shows them a page where they can enter their message and send it:

public ActionResult Create(string to)
{
    ViewData["recipientUsername"] = to;

    return View();
}

On the page that is displayed, the username is entered in to a hidden input field. When the user clicks 'send':

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection, string message)
{
    try
    {
        //do message stuff that errors out
    }
    catch
    {
        ModelState.AddModelErrors(message.GetRuleViolations()); //adding errors to modelstate
    }

    return View();
}

So now the error message is displayed to the user fine, however the url is changed in that it no longer has the querystring (/message/create). Again, this would be fine except that when the user clicks the refresh button, the page errors out as the Create action no longer has the 'to' parameter.

So I'm guessing that I need to maintain my querystring somehow. Is there any way to do this or do I need to use a different method altogether?

+1  A: 

Recommend you take a look at the PRG pattern which will help with this.

http://devlicio.us/blogs/tim_barcz/archive/2008/08/22/prg-pattern-in-the-asp-net-mvc-framework.aspx

Hightechrider
I see it says to add error messages in TempData instead of the Modelstate. I didn't think this fits with asp.net mvc's suggested error handling.
ajbeaven
+2  A: 

I assume you are doing something like...

<% Html.BeginForm("Create", "Controller") { %>

<% } %>

As you are creating the Form's action url through routing, the existing route values will be lost in the process. The easiest way to avoid this is by just using the parameterless version of BeginForm, since you are on the page you are posting to.

<% Html.BeginForm() { %>

<% } %>

This will use the current url, query string and all, as the ACTION of the form. Otherwise, you will need to pass in the route value to in the BeginForm overload.

Jab
Legend, that was exactly what I'd done. Thanks heaps.
ajbeaven