MVC Pass ViewBag to Controller

Nate Pet picture Nate Pet · Dec 1, 2011 · Viewed 43.8k times · Source

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.

Answer

Ryand.Johnson picture Ryand.Johnson · Dec 2, 2011

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