MVC Pass ViewBag to Controller
Asked Answered
F

1

7

I have a Viewbag that is a list that I am passing from the Controller to the View. The Viewbag is a list of 10 records in my case. 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. 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.

Fishbein answered 1/12, 2011 at 22:8 Comment(0)
L
13

Here is a quick example of using the 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:

@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>
 }
Ludovick answered 2/12, 2011 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.