kbye
kbye

Reputation: 59

Using one dropdownlist for two different forms in ASP MVC

Using MVC4, I have a drop-down list that contains a value a user may select. Then I have two different actions that I would like to pass that value into. How do I accomplish this, if it is even possible?

View:

@using (Html.BeginForm("Action1", "Controller", FormMethod.Post, new FormCollection()))
{
   @Html.DropDownList("Item", Model.GetListValues(Model.Items))
   <input type="submit" value="Goto Action1">
}

@using (Html.BeginForm("Action2", "Controller", FormMethod.Post, new FormCollection()))
{
   <input type="submit" value="Goto Action2">
}

Controller:

public Task<ActionResult> Action1(string item)
{
  //logic
}

public Task<ActionResult> Action2(string item)
{
  //logic
}

Right now, the code will allow me to pass in the value in the dropdown for the first form, but how do I include it in the second form? Might it involve the use of @Html.HiddenFor? I don't want to duplicate the drop-down list.

Upvotes: 0

Views: 347

Answers (1)

Jason Berkan
Jason Berkan

Reputation: 8884

With jQuery, all things are possible.

As you mentioned, add a hidden field to your second form. Then, add a jQuery script to update that field whenever the dropdown changes. You'll need to update your item names so they aren't duplicates, but other than that, your existing code will work.

$("#ItemDropdown").change(function () {
    $("#ItemHidden").val($("#ItemDropdown").val());
});

Upvotes: 3

Related Questions