ms87
ms87

Reputation: 17492

Dynamically assign controller and action to a form inside a partial view

I have a scenario where I need to render 3 different forms inside 3 jQuery-UI tabs, the structure of the forms and their model is identical, but I need to post the forms to a different controller and Action method depending on which tab the form is contained in. I've create a Partial View containing that form. Obviously I can create 3 different partial view posting to 3 different controllers however that seems very inefficient.

I'm wondering if its possible to somehow tell the Partial View to change the controller and action that the form contained in it posts to based on the tab it's contained in.

Something like:

<div id="tabs">
  <ul>
      <li><a href="#tabs-1">New Question </a><img src="@Url.Content("~/Content/images/FAQ.png")" /></li>
    <li><a href="#tabs-2">New Idea  </a> <img src="@Url.Content("~/Content/images/idea.png")" /></li>
    <li><a href="#tabs-3">New Bug</a> <img src="@Url.Content("~/Content/images/bug-icon.png")" /></li>
  </ul>
  <div id="tabs-1">
    @Html.Partial("_NewQuestionPartial")//this form posts to: Controller=Home and Action=Question
  </div>
  <div id="tabs-2">
    @Html.Partial("_NewQuestionPartial")//I want this form to post to: Controller=Support and Action=Idea
  </div>
  <div id="tabs-3">
    @Html.Partial("_NewQuestionPartial")//I want this form to post to: Controller=Support and Action=NewBug
  </div>
</div>

If I could somehow pass a variable to the partial view I can then set the action and controller with jQuery.

Is this at all possible? Any help is much appreciated.

Upvotes: 0

Views: 806

Answers (1)

Paul Taylor
Paul Taylor

Reputation: 5751

You can pass ViewBag fields (or better still, properties on your ViewModel) to the partial view that contains the name of the controller and view to post back to, and then in the view, insert these values into the appropriate arguments of the BeginForm helper.

In the main view:

@{
<div id="tabs">
     <ul>
        ...
     </ul>
     <div id="tabs-1">
          ViewBag.Controller = "Home";
          ViewBag.Action = "Question";
          Html.Partial("_NewQuestionPartial");
     </div>
     <div id="tabs-2">
          ViewBag.Controller = "Idea";
          ViewBag.Action = "Question";
          Html.Partial("_NewQuestionPartial");
     </div>
     <div id="tabs-3">
          ViewBag.Controller = "Idea";
          ViewBag.Action = "NewBug";
          Html.Partial("_NewQuestionPartial");
     </div>
</div>                
}

And in the partial view:

        @using (Html.BeginForm((string)ViewBag.Action, (string)ViewBag.Controller))
        {
            ...
        }

Upvotes: 1

Related Questions