[英]How to get MVC button to populate and display a table after being clicked
我已经花了4到5个小时来研究如何使其正常工作,但我根本无法弄清楚。 我想得到一个既有提交又有删除按钮的表单。 提交应将表单中的数据提交到同时填充和创建的表中,而“删除”按钮将删除最新添加的表。 我尝试执行的操作似乎无关紧要,只是行不通。 每当我单击“保存”按钮时,它只会重新加载页面,其中包含空的表单字段,而没有包含数据的表格。
我的控制器代码
public class PersonController : Controller
{
private static List<Person> Persons = new List<Person>();
public ActionResult Index()
{
return View();
}
public ActionResult Start()
{
return View("PersonData");
}
public ActionResult AddPerson(string firstName, string lastName, string birthDate)
{
Person p = new Person();
p.firstName = firstName;
p.lastName = lastName;
p.birthDate = birthDate;
if (Persons.Count > 0)
{
Persons.Add(p);
}
return View("PersonData");
}
public ViewResult DeletePerson()
{
if(Persons.Count > 0)
{
Persons.RemoveAt(0);
}
return View("PersonData");
}
}
我的查看代码
@model IEnumerable<UsingViewsandModels.Models.Person>
....
@using (Html.BeginForm("AddPerson", "PersonController"))
{
}
<form>
<label name="firstName">First Name: </label>
<input type="text" name="firstName" />
<br />
<label name="lastName">Last Name: </label>
<input type="text" name="lastName" />
<br />
<label name="birthDate">Birth Date: </label>
<input type="text" name="birthDate" />
<br />
<button type="submit" value="Submit" name="AddPerson" onclick="AddPerson()">Save</button>
<button type="submit" value="Delete" name="DeletePerson" onclick="DeletePerson()">Delete</button>
</form>
@if (Model != null && Model.Count() > 0)
{
<table>
<tr><th>FirstName</th><th>LastName</th><th>BirthDate</th></tr>
@foreach (UsingViewsandModels.Models.Person p in Model)
{
<tr>
<td>p.firstName)</td>
<td>p.lastName)</td>
<td>p.birthDate)</td>
</tr>
}
</table>
}
任何帮助将不胜感激。 我相当确定我只是个白痴,这很简单。
您有以下代码:
return View("PersonData");
这意味着: 返回名为“ PersonData”的视图 。
您没有向视图发送任何数据。 使用重载并将模型发送到您的视图,如下所示:
return View("PersonData", Persons);
现在你的观点可以访问所有数据Persons
,它会工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.