gpt4 book ai didi

c# - MVC 将 ViewBag 传递给 Controller

转载 作者:太空狗 更新时间:2023-10-29 20:03:29 26 4
gpt4 key购买 nike

我有一个 Viewbag,它是我从 Controller 传递到 View 的列表。在我的案例中,Viewbag 是一个包含 10 条记录的列表。一旦进入 View ,如果用户单击保存,我想将 View 的内容传递给 [HttpPost] 创建 Controller ,以便我可以创建 Viewbag 中的记录。我确定该怎么做。我已经为 1 项创建了新记录,但如何为多条记录创建新记录。

最佳答案

这是一个使用 ViewBag 的简单示例。我建议切换并使用模型来进行绑定(bind)。这是一篇很棒的文章。 Model Binding

获取方法:

    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>
}

关于c# - MVC 将 ViewBag 传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8348982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com