【问题标题】:MVC4 - Passing model between viewsMVC4 - 在视图之间传递模型
【发布时间】:2013-11-22 13:08:32
【问题描述】:

我有一个模型,我想要填写如下步骤: actionresult1(model)->actionresult2(model)-actionresult3(model)

我的模型是 Person:

public class Person{
  string FirstName {get;set;}
  string Lastname {get;set;}
  int Age {get;set;}
}

在我的 PersonController 中,我有三个 ActionResult:

public ActionResult FillFirstName(Person model)//First page where i start. Model is empty
    {
            return View("~/Views/FillFirstName.cshtml", model);           
    } 
public ActionResult FillLastName(Person model)//Second page, where first name is filled
    {
            return View("~/Views/FillLastName.cshtml", model);           
    } 
public ActionResult FillAge(Person model)//When i click submit button in FillLastName.cshtml view then it submits form here and model have filled only LastName and FirstName is empty.
    {
            return View("~/Views/FillAge.cshtml", model);           
    } 

而我的三个观点是:

1)FillFirstName.cshtml

@using (@Html.BeginForm("FillLastName", "Person"))
{
   @Html.TextBoxFor(m => m.FirstName)
   <input type="submit" name="Next" value="Next" />
}

2)FillLastName.cshtml

@using (@Html.BeginForm("FillAge", "Person"))
{
   @Html.TextBoxFor(m => m.LastName)
   <input type="submit" name="Next" value="Next" />
}

3)FillAge.cshtml

@using (@Html.BeginForm("NextAction", "Person"))
{
   @Html.TextBoxFor(m => m.Age)
   <input type="submit" name="Next" value="Next" />
}

问题:当我尝试在视图之间传递模型时,它只包含我在上一个视图中提交的数据。

原因:我已经形成了 2000 行,我想把它切成小块。

有没有什么办法可以使用 Viewbag 或 ModelState 或其他东西来让模型充满我在前几页提交的所有数据?有人可以给我一些例子吗? :)

【问题讨论】:

  • 如果您愿意,可以使用 Session

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-viewmodel


【解决方案1】:

HTTP 是无状态的 - 模型只能从当前请求中的内容绑定。因此,要访问最后一个控制器操作中的所有内容,您需要确保所有内容都在请求的表单发布中发送。使用隐藏字段在多个视图中保存数据:

FillLastName:

@using (@Html.BeginForm("FillAge", "Person"))
{
   @Html.HiddenFor(m => m.FirstName)
   @Html.TextBoxFor(m => m.LastName)
   <input type="submit" name="Next" value="Next" />
}

填充时间:

@using (@Html.BeginForm("NextAction", "Person"))
{
   @Html.HiddenFor(m => m.FirstName)
   @Html.HiddenFor(m => m.LastName)
   @Html.TextBoxFor(m => m.Age)
   <input type="submit" name="Next" value="Next" />
}

与使用会话状态等“伪状态”机制相比,这是一种更简洁、更传统的方式,可以在多个请求中持久保存表单数据。

【讨论】:

  • 对不起,我忘了说原因。我编辑了我的帖子:我已经形成了 2000 行,我想把它切成小块。所以,如果我必须将所有这些数据放在隐藏字段中,那么我最终会得到 10 个 2000 行的表格:P
  • 那么它真的需要在单独的动作中吗?为什么不将其拆分为逻辑分组的编辑器模板或部分?听起来您需要发布更多关于实际问题的信息。
  • 我用会话做到了。
猜你喜欢
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-02
  • 2012-11-16
  • 2021-05-26
相关资源
最近更新 更多