Asp.net-mvc – How to use ViewBag to pass list of data from View to controller

asp.net-mvcviewbag

how can i sen a list of items from a view to a controller to save it. i believe that i can use Viewbag but i dont realy no how to use ite to pass data from view to controller.

this is what i have tried
My view

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>ProductionOrderItem</legend>


    <div class="editor-label">
        @Html.Label("ProducrionOrderNo");
    </div>
    <div class="editor-field">
        @Html.TextBox("ProductionOrderNo", ViewBag.ProductionOrder as int)

    </div>

    <div class="editor-label">
       @Html.Label("OrderName")
    </div>
    <div class="editor-field">
        @Html.TextBox("OrderName", ViewBag.ProductionOrder as string)
    </div>
 <div class="editor-label">
       @Html.Label("OrderDate")
    </div>
    <div class="editor-field">
        @Html.TextBox("OrderDate", ViewBag.ProductionOrder as DateTime)
</div>
      <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

and my controller

   [HttpPost]
     public ActionResult Create(FormCollection collection)
     {
        ProductionRegistration pr = new ProductionRegistration();
        ProductionItem poi = new ProductionItem();

         poi = Viewbag.ProductionOrder;

         pr.SaveOrder(Conn, poi);
         return RedirectToAction("Index");

     }

Best Answer

You can't pass data from ViewBag/ViewData to the controller. It's one-way only (controller to view). The only way to get data back to the controller is to post it (post-body) or send it along in a querystring.

In fact, you should really avoid ViewBag as much as possible. It was added as a convenience and like most convenience methods, it's abused more often than not. Use a view model to both pass data to the view and accept data back from a post.

You strongly-type your view with:

@model Namespace.For.My.OrderViewModel

Then, you can use the [Foo]For methods of Razor to build your fields in a strongly-typed way:

<div class="editor-label">
    @Html.LabelFor(m => m.ProductionOrderNo);
</div>
<div class="editor-field">
    @Html.TextBoxFor(m => m.ProductionOrderNo)
</div>

And finally in your post action, you accept the view model as a param:

[HttpPost]
public ActionResult Create(OrderViewModel model)
{
    ...
}

And let MVC's modelbinder wire up the posted data for you.

No more dynamics. Everything is strongly-typed end-to-end, so if something goes wrong, you'll know it at compile-time, not run-time.