我正在尝试做一个简单的页面,将比较多个表单提交。
我有一个包含表单的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; }
}
}发布于 2015-04-02 21:24:27
我认为这是控制器和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
https://stackoverflow.com/questions/29399831
复制相似问题