ASP.NET MVC: Returning a View with an Intact Request

I am creating a web-based messaging application in ASP.NET and am experiencing some problems while displaying an error message to the user if they go to send a message and something is wrong.

The user can view the profiles of people, and then click "send message". The following action is called (url is / message / create? To = username) and shows them a page on which they can enter their message and send it:

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

On the displayed page, the username is entered into the hidden input field. When the user clicks Submit:

 [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 in order, however the URL has been changed in that it no longer has querystring (/ message / create). Again, this would be good, except that when the user clicks the refresh button, the page errors as the "Create" action no longer have the "to" parameter.

So, I assume that I need to somehow support my request. Is there a way to do this or do I need to use another method at all?

+4
source share
2 answers

I assume you are doing something like ...

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

When you create a form action URL through routing, existing route values ​​will be lost in the process. The easiest way to avoid this is to simply use the parameterless version of BeginForm , since you are on the page you are submitting.

 <% Html.BeginForm() { %> <% } %> 

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

+3
source

Recommend you take a look at the PRG template that will help with this.

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

+1
source

Source: https://habr.com/ru/post/1310305/


All Articles