ASP.NET MVC: Returning a view with querystring intact
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) a开发者_C百科nd 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?
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.
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
精彩评论