简体   繁体   English

MVC将ViewBag传递给Controller

[英]MVC Pass ViewBag to Controller

I have a Viewbag that is a list that I am passing from the Controller to the View. 我有一个Viewbag,它是我从Controller传递给View的列表。 The Viewbag is a list of 10 records in my case. Viewbag是我案例中的10条记录列表。 Once in the view, if the user clicks on save, I like to pass the content of the View to the [HttpPost] Create controller so that I can create records that are in the Viewbag. 进入视图后,如果用户点击了save,我想将View的内容传递给[HttpPost] Create控制器,以便我可以创建Viewbag中的记录。 I am on sure how to do this. 我确定如何做到这一点。 I have done the creation of a new record for 1 item but how do I do it for multiple records. 我已经为1个项目创建了一个新记录,但是如何为多个记录创建它。

Here is a quick example of using the ViewBag. 以下是使用ViewBag的快速示例。 I would recommend switching and using a model to do your binding. 我建议切换并使用模型进行绑定。 Here is a great article on it. 这是一篇很棒的文章。 Model Binding 模型绑定

Get Method: 获取方法:

    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 Method 发布方法

    [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        //only selected prodcuts will be in the collection
        foreach (var product in collection)
        {

        }
        return View();
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.NET MVC 5中将我的viewbag内容(一个巨大的表)从视图传递到控制器 - how to pass my viewbag content (a huge table) from view to controller, in ASP.NET MVC 5 Mvc 5单元测试 - 设置控制器的viewbag值 - Mvc 5 unit tests - set viewbag value of controller 将数组从JavaScript传递到viewbag并在控制器中使用 - pass array from JavaScript to viewbag and use it in controller 将viewbag从动作控制器传递到局部视图 - Pass viewbag to partial view from action controller 将列表从 Controller 传递到使用 ViewBag 进行查看 - Pass List From Controller to View Using ViewBag MVC 5 asp.net,从控制器到视图的viewbag无法正常工作 - MVC 5 asp.net, viewbag from controller to view is not working 将ViewBag中的消息从控制器传递到ASP.Net MVC中的视图 - Passing message in ViewBag from controller to view in ASP.Net MVC 从操作控制器将ViewBag传递到PartialView,该控制器返回该PartialView - Pass ViewBag to PartialView from action controller that returns that PartialView 如何将ViewBag从控制器传递到View(Ajax Url) - How can I pass a ViewBag from controller to View(Ajax Url) 如何将foreach中的viewbag值从视图传递到表单提交的控制器 - How to pass viewbag values in a foreach from view to controller on form submit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM