我有以下GET和POST操作方法: -
public ActionResult Create(int visitid)
{
VisitLabResult vlr = new VisitLabResult();
vlr.DateTaken = DateTime.Now;
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description");
return View();
}
//
// POST: /VisitLabResult/Create
[HttpPost]
public ActionResult Create(VisitLabResult visitlabresult, int visitid)
{
try
{
if (ModelState.IsValid)
{
visitlabresult.VisitID = visitid;
repository.AddVisitLabResult(visitlabresult);
repository.Save();
return RedirectToAction("Edit", "Visit", new { id = visitid });
}
}
catch (DbUpdateException) {
ModelState.AddModelError(string.Empty, "The Same test Type might have been already created,, go back to the Visit page to see the avilalbe Lab Tests");
}
ViewBag.LabTestID = new SelectList(repository.FindAllLabTest(), "LabTestID", "Description", visitlabresult.LabTestID);
return View(visitlabresult);
}
目前,视图显示相关字段只能创建一个对象,但我如何定义对象列表而不是一个对象,以便能够在同一“创建”请求中快速添加例如10个对象。 我的创建视图如下所示: -
@model Medical.Models.VisitLabResult
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@section scripts{
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>VisitLabResult</legend>
<div class="editor-label">
@Html.LabelFor(model => model.LabTestID, "LabTest")
</div>
<div class="editor-field">
@Html.DropDownList("LabTestID", String.Empty)
答案 0 :(得分:10)
您的viewModel
public class LabResult
{
public int ResultId { get; set; }
public string Name { get; set; }
//rest of the properties
}
您的控制器
public class LabController : Controller
{
//
// GET: /Lab/ns
public ActionResult Index()
{
var lst = new List<LabResult>();
lst.Add(new LabResult() { Name = "Pravin", ResultId = 1 });
lst.Add(new LabResult() { Name = "Pradeep", ResultId = 2 });
return View(lst);
}
[HttpPost]
public ActionResult EditAll(ICollection<LabResult> results)
{
//savr results here
return RedirectToAction("Index");
}
}
您的观点
@model IList<MvcApplication2.Models.LabResult>
@using (Html.BeginForm("EditAll", "Lab", FormMethod.Post))
{
<table>
<tr>
<th>
ResultId
</th>
<th>
Name
</th>
</tr>
@for (int item = 0; item < Model.Count(); item++)
{
<tr>
<td>
@Html.TextBoxFor(modelItem => Model[item].ResultId)
</td>
<td>
@Html.TextBoxFor(modelItem => Model[item].Name)
</td>
</tr>
}
</table>
<input type="submit" value="Edit All" />
}
您的视图将呈现如下,这个基于数组的命名约定使得Defaultbinder可以将其转换为ICollection作为第一个动作参数EditAll
<tr>
<td>
<input name="[0].ResultId" type="text" value="1" />
</td>
<td>
<input name="[0].Name" type="text" value="Pravin" />
</td>
</tr>
<tr>
<td>
<input name="[1].ResultId" type="text" value="2" />
</td>
<td>
<input name="[1].Name" type="text" value="Pradeep" />
</td>
</tr>
答案 1 :(得分:0)
如果我理解你的问题,
您希望将视图更改为模型对象@model列表的列表,然后使用循环或者您希望这样做,为每个对象创建所需的编辑器
然后在您的控制器中,您创建的接收参数也将是您的模型列表。