43

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?

2 Answers 2

96

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)
2
  • @Johan is there any big difference between the 2?
    – Vahx
    May 19, 2016 at 9:30
  • 1
    @I meant more along the line of security, performance or anything? is one an old way or a new way?
    – Vahx
    May 19, 2016 at 9:35
1

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.