Asp Mvc post将项目添加到列表中

时间:2015-09-03 18:28:21

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

我开始学习asp网。我想在表格中显示列表并在此页面上创建新行

我创建模型

  public class Student
{
    public string Name { get; set; }
    public string Surname { get; set; }

}

然后查看

@model IEnumerable<WebApplication1.Models.Student>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Surname)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Surname)
            </td>
        </tr>
    }
</table>


<div class="form-horizontal">
    @using (Html.BeginForm())
    {

        <div class="form-group">
            <label class="col-md-2">Имя</label>
            @Html.TextBox("name", null, new {@class = "form-control col-lg-4"})
        </div>

        <div class="form-group">
            <label class="col-md-2">Фамилия</label>
            @Html.TextBox("surname", null, new {@class = "form-control col-lg-4"})
        </div>
        <button type="submit" class="btn btn-default">Добавить</button>
    }
</div>

<div class="panel-footer">
    <h3>@ViewBag.Msg</h3>
</div>

和控制器

  List<Student> Students=new List<Student>
    {
        new Student() {Name = "1",Surname = "1"},
        new Student() {Name = "2",Surname = "2"},
        new Student() {Name = "3",Surname = "3"}
    }; 
    // GET: Home
    public ActionResult Index()
    {
        return View(Students);
    }

    [HttpPost]
    public ActionResult Index(string name,string surname)
    {
        Students.Add(new Student() {Name = name,Surname = surname});
        @ViewBag.Msg = "User add : " + name +" "+ surname;
        return View(Students);
    }

所有工作都很好但是当我添加新行的最后一行重新创建时(在我的集合中只添加一行)。哪里错了?抱歉我的英文不好

2 个答案:

答案 0 :(得分:3)

列表是控制器类的私有变量,因为在每次页面请求时,都会创建一个新的控制器实例,每次使用初始值初始化列表项,然后只是新的值将被添加到它 您可以将列表定义为静态,以防止对每个请求进行初始化:

static List<Student> Students=new List<Student>
{
    new Student() {Name = "1",Surname = "1"},
    new Student() {Name = "2",Surname = "2"},
    new Student() {Name = "3",Surname = "3"}
}; 

答案 1 :(得分:1)

您不会将数据保存在任何位置,因此每次请求都会重置数据。这个属性:

List<Student> Students

是一个类级属性。每次创建类的实例时,它都会被初始化。并且为服务器的每个单独请求创建控制器类的实例。所以这里发生的是:

  1. 用户请求页面
  2. 创建控制器对象,初始化列表
  3. Controller将列表返回给用户
  4. 用户发布新项目
  5. 创建控制器对象,初始化列表
  6. Controller将第4项添加到列表中
  7. Controller将列表返回给用户
  8. 每个帖子都重复步骤4-7。

    为了保留您的数据,您需要将其存储在某个位置。数据库是理想的。但是还有其他选择,取决于你正在做的范围。

    例如,只是为了测试功能,您可以将其存储在会话状态中。在这种情况下,它将为每个用户会话重置,而不是为每个请求重置。

    或许您可以创建列表static,在这种情况下,它将在整个应用程序实例中用于所有用户。 (但是线程安全的。)

相关问题