我有一个 Viewbag,它是我从 Controller 传递到 View 的列表。在我的案例中,Viewbag 是 10 条记录的列表。一旦进入视图,如果用户单击保存,我喜欢将视图的内容传递给 [HttpPost] 创建控制器,以便我可以创建 Viewbag 中的记录。我很确定如何做到这一点。我已经为 1 个项目创建了一个新记录,但是我该如何为多个记录创建一个新记录。
问问题
44144 次
1 回答
13
这是一个使用 ViewBag 的快速示例。我建议切换并使用模型来进行绑定。这是一篇很棒的文章。模型绑定
获取方法:
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
List<string> items = new List<string>();
items.Add("Product1");
items.Add("Product2");
items.Add("Product3");
ViewBag.Items = items;
return View();
}
发布方法
[HttpPost]
public ActionResult Index(FormCollection collection)
{
//only selected prodcuts will be in the collection
foreach (var product in collection)
{
}
return View();
}
html:
@using (Html.BeginForm("Index", "Home"))
{
foreach (var p in ViewBag.Items)
{
<label for="@p">@p</label>
<input type="checkbox" name="@p" />
}
<div>
<input id='btnSubmit' type="submit" value='submit' />
</div>
}
于 2011-12-02T14:22:17.023 回答