这是我的模型类,有两个类Employee和Employee list
namespace EditMultiplerecords.Models
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Employeelist : IEnumerable<Employee>
{
public List<Employee> employee { get; set; }
public IEnumerator<Employee> GetEnumerator()
{
return employee.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return employee.GetEnumerator();
}
}
}
这是我的视图,我正在使用javascript编写代码进行编辑
@model EditMultiplerecords.Models.Employeelist
@{
ViewBag.Title = "Homepage";
}
<link href="../../Content/StyleSheet1.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.editor input').blur(function () {
$(this).hide();
$(this).closest('p').find('label').html($(this).val()).show();
});
$('.editor label').click(function () {
$(this).hide();
$(this).closest('p').find('input').show();
});
});
</script>
@foreach (var item in Model)
{
using (Html.BeginForm())
{
<div class="editor">
<p>
@Html.HiddenFor(x => item.Id)
@Html.LabelFor(x => item.Name, item.Name)
@Html.EditorFor(x => item.Name)
<input type="submit" value="OK" />
</p>
</div>
}
@* @Html.Partial("Details", item);*@
}
这个控制器类
public ActionResult Homepage()
{
Employeelist el = new Employeelist();
el.employee = new List<Employee>();
el.employee.Add(new Employee { Id = 1, Name = "Rahul" });
el.employee.Add(new Employee { Id = 2, Name = "America" });
el.employee.Add(new Employee { Id = 3, Name = "NewJersey" });
return View(el);
}
[HttpPost]
public ActionResult Homepage(Employeelist el)
{
return View(el);
}
我的问题是当我编辑Rahul或America或NewJersey时,在Post Action上获取一个空列表,其中包含空值而非更新列表
答案 0 :(得分:0)
您需要在@foreach (var item in Model)
内添加using (Html.BeginForm())
循环以接受修改后的列表
using (Html.BeginForm())
{
@foreach (var item in Model)
{
<div class="editor">
<p>
@Html.HiddenFor(x => item.Id)
@Html.LabelFor(x => item.Name, item.Name)
@Html.EditorFor(x => item.Name)
</p>
</div>
}
}
<input type="submit" value="OK" />
@* @Html.Partial("Details", item);*@
- 编辑接受formCollection
[HttpPost]
public ActionResult Homepage(FormCollection formCollection)
{
var itemid = formCollection.GetValue("item.id");
var itemname= formCollection.GetValue("item.name");
---//use values to send it back to view----
return View();
}