简体   繁体   English

ASP.NET MVC:返回查询字符串完整的视图

[英]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. 我正在ASP.NET中创建一个消息传递Web应用程序,如果他们发送消息并且出现错误,则在向用户显示错误消息时会遇到一些问题。

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: 调用以下操作(url是/ message / create?to = username)并向他们显示一个页面,他们可以在其中输入消息并发送它:

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). 所以现在错误消息显示给用户很好,但是更改了url,因为它不再具有查询字符串(/ 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. 同样,这很好,除非当用户单击刷新按钮时,页面错误,因为Create操作不再具有'to'参数。

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. 当您通过路由创建表单的操作URL时,现有路由值将在此过程中丢失。 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. 避免这种情况的最简单方法是使用BeginForm的无参数版本,因为您在发布的页面上。

<% Html.BeginForm() { %>

<% } %>

This will use the current url, query string and all, as the ACTION of the form. 这将使用当前url,查询字符串和all作为表单的ACTION。 Otherwise, you will need to pass in the route value to in the BeginForm overload. 否则,您需要将路由值传递to BeginForm重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM