MVC Transfer Data Between Views

前端 未结 3 881
忘掉有多难
忘掉有多难 2021-01-15 16:02

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.

<
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-15 16:49

    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(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 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>" %>
    
    
        Index
    
    
    
        

    Products

    <% foreach (var p in Model) { %>
    <%= Html.Encode( p.ProductName ) %>
    <% } %> <%= 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"; %> <% } %>
    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

提交回复
热议问题