MVC Pass ViewBag for controller

I have a Viewbag, which is a list that I pass from the controller to the view. Viewbag is a list of 10 entries in my case. As soon as you see, if the user clicks on save, I like to transfer the contents of the view to the [HttpPost] Create controller, so that I can create entries that are in the Viewbag. I know exactly how to do this. I did create a new entry for one item, but how to do it for multiple entries.

+6
source share
1 answer

Here is a quick example of using ViewBag. I would recommend switching and using the model for snapping. Here is a great article. 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(); } 

Shipping 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> } 
+12
source

Source: https://habr.com/ru/post/902873/


All Articles