asp.net-mvc 重定向到操作并需要传递数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3363842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:23:57  来源:igfitidea点击:

Redirect to action and need to pass data

asp.net-mvcredirect

提问by Dylan Beattie

I have a controller that handles three actions that are specific to my problem.

我有一个控制器来处理三个特定于我的问题的操作。

The first is the edit action which returns a view with an HTML form that the user can edit properties on the given item.

第一个是编辑操作,它返回一个带有 HTML 表单的视图,用户可以在该视图中编辑给定项目的属性。

The second is the update action which accepts the post back form the browser and updates the database. When the update is successful we do a redirect to action.

第二个是更新操作,它接受来自浏览器的回发并更新数据库。更新成功后,我们会重定向到操作。

The third is the show action which shows the details of the given item. This action is where we get redirected to after a successful update.

第三个是显示动作,显示给定项目的详细信息。此操作是我们在成功更新后重定向到的位置。

The flow is:

流程是:

Show -> Edit -> Update (Sucess: y -> redirect to Show, n -> return Edit)

显示 -> 编辑 -> 更新(成功:y -> 重定向到显示,n -> 返回编辑)

What I want to achieve is to have a flag tripped when the update was successful so that on the next Show view I can display a confirmation message for the user. The problem is that I'm not 100% sure on the best way to carry that data over the RedirectToAction() call. One thought I had was using a query string? We are already carrying variables around with the query string for another purpose but part of my is skeptical to abuse that. The call to the redirect is below.

我想要实现的是在更新成功时触发一个标志,以便在下一个 Show 视图中我可以为用户显示一条确认消息。问题是我不是 100% 确定通过 RedirectToAction() 调用携带该数据的最佳方式。有人认为我在使用查询字符串吗?我们已经在查询字符串中携带变量用于其他目的,但我的一部分怀疑滥用它。对重定向的调用如下。

RouteValueDictionary dict = Foo.GetRouteValues(bar);

RedirectToAction("Show", dict);

I've read this question as well but am leary about using the TempData property if I don't have to.

我也读过这个问题,但如果我不需要的话,我对使用 TempData 属性很谨慎。

Question

Thanks for some suggestions!

谢谢你的一些建议!

回答by Dylan Beattie

EDIT: Sorry, didn't originally see your note about not wanting to use TempData.

编辑:抱歉,最初没有看到您关于不想使用 TempData 的说明。

In a nutshell - do you want your message to reappear if the client refreshes/reloads the page they've been redirected to?

简而言之 - 如果客户端刷新/重新加载他们被重定向到的页面,您是否希望您的消息重新出现?

If you do, then use the querystring, something like:

如果这样做,则使用查询字符串,例如:

return(RedirectToAction("Index", new { message = "hi there!" }));

and then either define

然后要么定义

public ActionResult Index(string message) { }

or explicitly pull out Request.QueryString["message"] and pass it to the View via ViewData in the usual way. This will also work on browsers that aren't accepting cookies from your site.

或者显式拉出 Request.QueryString["message"] 并以通常的方式通过 ViewData 将其传递给 View。这也适用于不接受来自您网站的 cookie 的浏览器。

If you DON'T want the message to display again, then ASP.NET MVC 1.0 provides the TempData collection for this exact purpose.

如果您不希望再次显示该消息,则 ASP.NET MVC 1.0 将为此确切目的提供 TempData 集合。

TempData property values are stored in session state until the next request from the same browser, after which they are cleared - so if you put something in TempData immediately before returning RedirectToAction, it'll be available on the result of the redirect but will be cleared immediately afterwards.

TempData 属性值存储在会话状态中,直到来自同一浏览器的下一个请求,之后它们被清除 - 因此,如果您在返回 RedirectToAction 之前立即将某些内容放入 TempData,它将在重定向结果中可用,但将被清除紧接着。

Here's a simple change to the HomeController in the ASP.NET MVC startup project:

下面是对 ASP.NET MVC 启动项目中 HomeController 的简单改动:

public ActionResult Index() {
    ViewData["Message"] = "Welcome to ASP.NET MVC!";
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string submitButton) {
    TempData["message"] = "You clicked " + submitButton;
return(RedirectToAction("Index"));
}

public ActionResult About() {
    return View();
}

and the corresponding view /Views/Home/Index.aspx should contain something like this:

相应的视图 /Views/Home/Index.aspx 应该包含如下内容:

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
  <% if (TempData["message"] != null) { %>
    <p><%= Html.Encode(TempData["message"]) %></p>
  <% } %>
  <% using (Html.BeginForm()) { %>
    <input type="submit" name="submitButton" value="Button One" />
    <input type="submit" name="submitButton" value="Button Two" />
  <% } %>
</asp:Content>

You'll notice the TempData message is displayed immediately following a POST-REDIRECT-GET sequence, but if you refresh the page, it won't be displayed again.

您会注意到 TempData 消息在 POST-REDIRECT-GET 序列之后立即显示,但如果您刷新页面,它将不会再次显示。

Note that this behaviour has changed in ASP.NET MVC 2 - see "Passing State between Action Methods" in this articlefor more information.

请注意,这种行为在ASP.NET MVC 2已经改变-见“传递行动方法之间的状态”这篇文章以了解更多信息。

回答by wal

Never been a fan of TempDataeither and additionally I didnt want to pass the success flag in the URL as I didnt want to see

从来TempData都不是他们的粉丝,另外我不想在 URL 中传递成功标志,因为我不想看到

App/Settings?saveSuccess=true

应用程序/设置?saveSuccess=true

in the URL bar of the browser.

在浏览器的 URL 栏中。

My solution uses a temporary cookie:

我的解决方案使用临时 cookie:

[HttpPost]
public ActionResult Settings(SettingsViewModel view)
{
    if (ModelState.IsValid)
    {
        //save
        Response.SetCookie(new HttpCookie("SettingsSaveSuccess", ""));
        return RedirectToAction("Settings");
    }
    else
    {
        return View(view);
    }     
}

and in the corresponding Get action check for the presence of this Cookie and delete it:

并在相应的 Get 操作中检查此 Cookie 的存在并删除它:

[HttpGet]
public ActionResult Settings()
{
    var view = new SettingsViewModel();
    //fetch from db and do your mapping
    bool saveSuccess = false;
    if (Request.Cookies["SettingsSaveSuccess"] != null)
    {
        Response.SetCookie(new HttpCookie("SettingsSaveSuccess", "") { Expires = DateTime.Now.AddDays(-1) });
        saveSuccess = true;
    }
    view.SaveSuccess = saveSuccess;
    return View(view);
}

nb this can be a fairly slipperly slope if you start to pass anything more complex than a boolean flag

注:这可能是一个相当slipperly斜率,如果你开始传递什么比一个布尔标志更复杂