MVC 在视图之间传输数据

发布于 2024-09-06 21:53:26 字数 316 浏览 10 评论 0原文

我刚刚开始学习 MVC,并试图了解它是如何工作的。

我不想将用户发送到所有编辑、插入和列表操作的不同视图。

在我的示例应用程序中,视图包含项目列表,列表下方有一个带有操作“{Controller}/Create”的表单(用于插入新项目),但没有创建视图。

当用户插入新项目时,它会使用 httpverb post 发布到 Create 操作,并创建该项目并使用 RedirectToAction 方法返回到 List 操作。

但我无法以这种方式向用户显示任何消息(错误、信息等),因为我无法在“创建”操作和“列表”操作之间传递数据。我怎样才能做到这一点?

I just started to learn MVC and am trying to understand how it works.

I don't want to send users to different views for all edit, insert and list operations.

In my sample application a View contains a list of items and below the list there is a form (for inserting new items) with action "{Controller}/Create" but there is no Create View.

When a user inserts a new item it posts to the Create action with httpverb post and creates the item and returns back to the List action with RedirectToAction method.

But I can not show any message(error, information etc) to the user in this style because I can not pass data between Create action and List action. How can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

国粹 2024-09-13 21:53:26

您需要使用 Post Redirect Get PRG 模式。

请阅读 Kazi Manzur Ra​​shid 撰写的这篇博文中的使用 PRG 模式进行数据修改部分。
http: //weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx

此方法使用 TempData 来维护重定向之间的 ModelState 数据。

[HttpPost, ValidateAntiForgeryToken, ExportModelStateToTempData]
public ActionResult Create(FormCollection form)
{
    Product p = new Product();

    if (TryUpdateModel<IProductModel>(p))
    {
        productRepository.CreateProduct( p );
    }
    else
    {
        // add additional validation messages as needed
        ModelState.AddModelError("_generic", "Error Msg");
    }

    return RedirectToAction("Index");
}

这是您的 Index 操作方法。

[ImportModelStateFromTempData]
public ActionResult Index()
{
    IList<Product> products = productRepository.GetAll();
    return View("Index", products);
}

这是您的 Index 视图。

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<Product>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Products</h2>

    <% foreach (var p in Model) { %>
        <div><%= Html.Encode( p.ProductName ) %></div>
    <% } %>

    <%= Html.ValidationSummary("Please correct the errors", new { id = "valSumCreateForm" }) %>
    <% using (Html.BeginForm("Create", "Product")) { %>
        Product Name: <%= Html.TextBox("ProductName") %>
        <%= Html.AntiForgeryToken() %>
        <% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %>
    <% } %>
</asp:Content>
  1. ImportModelStateFromTempData
    和ExportModelStateToTempData
    属性有助于模型迁移
    状态重定向之间的错误。这个
  2. <% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %> 将 MVC 表单与其相应的验证摘要相关联。

您也可以在这里查看我对此的另一个答案。
ViewModel 与 ASP.NET MVC2 中的 SelectList 绑定

如果您有任何疑问,请告诉我。
-索伊

You need to use Post Redirect Get PRG pattern.

Please read this Use PRG Pattern for Data Modification section in this blog post by Kazi Manzur Rashid.
http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx

This approach uses TempData to maintain ModelState data between redirects.

[HttpPost, ValidateAntiForgeryToken, ExportModelStateToTempData]
public ActionResult Create(FormCollection form)
{
    Product p = new Product();

    if (TryUpdateModel<IProductModel>(p))
    {
        productRepository.CreateProduct( p );
    }
    else
    {
        // add additional validation messages as needed
        ModelState.AddModelError("_generic", "Error Msg");
    }

    return RedirectToAction("Index");
}

And here is your Index action method.

[ImportModelStateFromTempData]
public ActionResult Index()
{
    IList<Product> products = productRepository.GetAll();
    return View("Index", products);
}

And here is your Index view.

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IList<Product>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>Products</h2>

    <% foreach (var p in Model) { %>
        <div><%= Html.Encode( p.ProductName ) %></div>
    <% } %>

    <%= Html.ValidationSummary("Please correct the errors", new { id = "valSumCreateForm" }) %>
    <% using (Html.BeginForm("Create", "Product")) { %>
        Product Name: <%= Html.TextBox("ProductName") %>
        <%= Html.AntiForgeryToken() %>
        <% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %>
    <% } %>
</asp:Content>
  1. The ImportModelStateFromTempData
    and ExportModelStateToTempData
    attributes helps transfer model
    state errors between redirects. This
  2. <% ViewContext.FormContext.ValidationSummaryId = "valSumCreateForm"; %> associates the MVC Form with its corresponding Validation Summary.

You can check another answer by me on this here as well.
ViewModel with SelectList binding in ASP.NET MVC2

Let me know if you have any question.
-Soe

梦里梦着梦中梦 2024-09-13 21:53:26

大多数 MVC 框架都能够在下一个请求时临时存储少量数据,就是为了这个目的。在 ASP.NET MVC 中,它称为 TempData,在 Rails 中,它称为 :flash 等。

Most MVC frameworks have the ability to temporarily store a small bit of data just through the next request, for just this purpose. In ASP.NET MVC its called TempData, in Rails it's called :flash, etc.

听风吹 2024-09-13 21:53:26

本文介绍如何使用TempData:

最烦人的事情之一
Web编程中处理错误
在表格上。更具体地说,你想要
显示错误消息,但是您
想要保留之前输入的内容
数据。我们都有过这样的经历
在包含 35 的表格上犯了一个错误
字段,仅呈现一个
一堆错误消息和一个新的,
空白表格。 MVC 框架提供 TempData 作为存储先前输入的信息的位置,以便可以重新填充表单。
ViewState 实际制作的东西
在 Web 表单中非常容易,因为保存
控件的内容很漂亮
非常自动。 ... TempData 是一个字典,
很像非类型化的 ViewData。
但是,TempData 的内容仅
为单个请求而活,然后
它们已被删除。

This article explains how to use TempData:

One of the more annoying things to
deal with in Web programming is errors
on a form. More specifically, you want
to display error messages, but you
want to keep the previously entered
data. We've all had the experience of
making a mistake on a form that has 35
fields, only to be presented with a
bunch of error messages and a new,
blank form. The MVC Framework offers TempData as a place to store the previously entered information so that the form can be repopulated. This is
something that ViewState actually made
very easy in Web Forms, since saving
the contents of controls was pretty
much automatic. ... TempData is a dictionary,
much like the untyped ViewData.
However, the contents of TempData only
live for a single request and then
they're deleted.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文