2015-04-01 61 views
0

我试图做一个简单的页面,将比较多个表单提交。ASP.NET跨会话列表

我有一个表格的HTML页面,并为表单提交列表中的每个项目生成div的for循环。该列表从控制器传递。我试图维护控制器中的列表,而不是依赖数据库。

当我尝试重新提交表单时,应该将另一个对象添加到列表中,列表重新初始化。

在调试中,我发现表单在提交时是空的。我不确定是否有正确的术语,但似乎只要呈现视图就会清空列表。有没有办法维护列表内容?

我知道有更好的方法来做到这一点,并欢迎提供任何建议。我仍然在学习,所以认为容易。

谢谢!

这是简化的控制器。

namespace MvcApplication2.Controllers 
{ 
public class HomeController : Controller 
    { 
     List<paymentPlan> plansList = new List<paymentPlan>(); 
     public ActionResult Index() 
     { 
      return View(plansList); 
     } 

     [HttpPost] 
     public ActionResult Index(FormCollection collection) 
     { 
      paymentPlan Project = new paymentPlan(); 
      Project.customerName = Convert.ToString(collection["customerName"]); 
      plansList.Add(Project); 
      return View(plansList); 
     } 

    } 
} 

这是我的简化视图。

@model List<MvcApplication2.Models.paymentPlan> 
@using (Html.BeginForm("index", "home", FormMethod.Post, new { Id = "signupForm" })) 
{ 
    <label for="customerName">Customer Name:</label> 
    <input type="text" name="customerName" class="form-control required" /> 
    @Html.ValidationSummary(true) 
    <input type="submit" value="Calculate" class="btn btn-primary" /> 
} 

@{ 
    bool isEmpty = !Model.Any(); 
    if (!isEmpty) 
    { 
     foreach (var i in Model) 
     { 
      <div> 
       Name: @i.customerName 
      </div> 
     } 
    } 
} 

这是我的简化模型。

namespace MvcApplication2.Models 
{ 

    public class paymentPlan 
    { 
     public string customerName { get; set; } 
    } 
} 
+0

你不能_ “保持在控制器列表” _。客户端的每个请求都初始化控制器的新实例,并因此初始化集合的新实例。我也建议你去MVC网站,通过教程学习一些基本知识 – 2015-04-01 20:25:52

+0

感谢您的回应。这就是我的预期。数据库是必需的,还是您有任何其他可能的解决方案? – cougheeCup 2015-04-01 20:28:41

回答

0

我认为这是一个控制器和asp.Net MVC生命周期的问题! 控制器生命周期与请求相同,对于每个请求都创建一个新的控制器,一旦完成工作,它就被处置! 所以尽量消除这种List<paymentPlan> plansList = new List<paymentPlan>();TempData[]ViewData[]Session[]这样的工作:

控制器

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     Session["plansList"] = ((List<paymentPlan>)Session["plansList"])!=null? (List<paymentPlan>)Session["plansList"] : new List<paymentPlan>(); 
     return View((List<paymentPlan>)Session["plansList"]); 
    } 

    [HttpPost] 
    public ActionResult Index(FormCollection collection) 
    { 
     paymentPlan Project = new paymentPlan(); 
     Project.customerName = Convert.ToString(collection["customerName"]); 
     ((List<paymentPlan>)Session["plansList"]).Add(Project); 
     return View(plansList); 
    } 

} 

检查:http://www.asp.net/mvc/overview/getting-started/lifecycle-of-an-aspnet-mvc-5-application

+0

谢谢,这有助于引导我走向正确的方向。 – cougheeCup 2015-04-02 20:39:46