Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass multiple parameters in Html.BeginForm MVC

I have something like this:

public ActionResult Create(int clubid) {   var club = db.Clubs.Single(c=>c.Id == clubid);   ViewBag.Club = club;   Competition comp = db.Competitions.Create();   return View(comp) } 

and in my .cshtml:

@Model Models.Competition ... @Using(Html.BeginForm()) {   ...   <input type="submit" value="Save" /> } 

This works fine with the following Post Action:

[HttpPost] public ActionResult Create(Competition comp) {   if (ModelState.IsValid){...}    return RedirectToAction(...);  } 

However, I want to pass an additional parameter from the @ViewBag.Club object:

[HttpPoSt] public ActionResult Create(int clubid, Competition comp){...} 

How do I code this in the BeginForm?

like image 483
Andy Johnston Avatar asked Jun 09 '13 20:06

Andy Johnston


People also ask

Can we use multiple BeginForm in MVC?

Thanks for your help ! Multiple form tags should work fine in MVC unless they are nested.

How many parameters are used in HTML BeginForm?

It does hold two parameters, but those are for the controller name and the controller action.

How do you pass a route value in HTML BeginForm?

The value will only be added as query string values if its FormMethod. Get (and you can remove the route values from the BeginForm() method). But what is the point of this - they are hidden inputs, not editable values.

What is @using HTML BeginForm ()) in MVC?

BeginForm(HtmlHelper) Writes an opening <form> tag to the response. The form uses the POST method, and the request is processed by the action method for the view. BeginForm(HtmlHelper, String, String, Object, FormMethod, Object)


1 Answers

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id) 

or

 @using(Html.BeginForm("action", "controller",                        new { clubid = @Viewbag.Club.id }, FormMethod.Post, null) 
like image 142
Johan Avatar answered Oct 02 '22 11:10

Johan