MVC传递ViewBag到控制器

7

我有一个Viewbag,它是一个列表,我将其从控制器传递到视图中。 在我的情况下,Viewbag是10条记录的列表。一旦在视图中,如果用户点击保存,我想将视图的内容传递给[HttpPost] Create控制器,以便我可以创建在Viewbag中的记录。我不确定如何做到这一点。我已经为1个项目创建了新记录,但如何为多个记录执行此操作呢?

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();
    }

提交方式为Post

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接