我是 MVC 的新手,我有一些我无法理解的问题。下面的代码是我想要达到的:
模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace testapplication.Models {
public class testModel {
public class SystemUser {
public string Name { get; set; }
public string Email { get; set; }
}
public static List<SystemUser> list1;
public static void CreateList1() {
list1 = new List<SystemUser>();
}
public static void FillList1() {
SystemUser firstUser = new SystemUser();
firstUser.Name = "name";
firstUser.Email = "email@address.com";
list1.Add(firstUser);
}
public static List<SystemUser> list2 = new List<SystemUser>();
public static void FillList2() {
SystemUser firstUser = new SystemUser();
firstUser.Name = "name";
firstUser.Email = "email@address.com";
list2.Add(firstUser);
}
public static string list3 = "test";
}
}
控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using testapplication.Models;
namespace testapplication.Controllers {
public class HomeController : Controller {
public ActionResult Index() {
testModel.CreateList1();
testModel.FillList1();
testModel.FillList2();
var var1 = testModel.list1;
var var2 = testModel.list2;
var var3 = testModel.list3;
return View();
}
[HttpPost]
public ActionResult Index(string test) {
var var1 = testModel.list1;
var var2 = testModel.list2;
var var3 = testModel.list3;
return View();
}
}
}
看法:
<h2>Index</h2>
@using (Html.BeginForm("Index", "Home", FormMethod.Post)) {
<input type="submit" value="Submit" />
}
在 POST 方法 list1 之前,list2 和 list3 可以,但在 Post list1 为 null 之后,list2 为空(创建实例)并且 list3 可以。这是为什么?我希望在 POST 之前和之后具有相同的值。