我開始學習asp網絡。我想在表中顯示列表,而這個頁面Asp Mvc post將項目添加到列表
我創建模型
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);
}
所有的工作很好,但是當創建新行我添加新行最後一行重新創建(在我的收藏中只添加一行)。我錯在哪裏?對不起我的英文不好
你想要什麼? –
我想按下按鈕並在我的表格中添加行 – user3351644