0

How can I pass a value in ViewBag to controller via HTML.BeginForm()?

@using (Html.BeginForm("SaveServiceItemCategory", "Admin", 
                       FormMethod.Post, new { Sku = @ViewBag.SkuCategory  }))
{
    <span>Service Item Sku : @ViewBag.SkuCategory</span>
}

Controller

public ActionResult SaveServiceItemCategory(FormCollection formCollection, 
                                            string Sku)
{}

I am getting Sku as null, and not the value in ViewBag.

How can this be solved?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Nanu
  • 3,010
  • 10
  • 38
  • 52

1 Answers1

3

There is no variant of BeginForm that accepts values to be posted.

The IDictionary collection parameter for BeginForm is for htmlAttributes. Check your HTML code and you'll probably see an attribute on the form named Sku. These attributes don't get posted to the server.

You need to create a form element to contain your data to be posted.

@Html.Hidden("Sku", @ViewBag.SkuCategory);
Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162
  • This does not seem to post to the server. Only items from the model are posting. – mad moe Jul 13 '12 at 18:31
  • 1
    All form fields are posted. The default binder might not attach them to the model specified but you'll see they're available in the FormCollection. – Jamie Dixon Jul 13 '12 at 21:38