1

Hi i have a partial view that has a search form, the search form redirects to action "Search" in Controller "Search".. I am using this form in multiple locations but i need the action "Search" in Controller "Search" to pick up where this form is used to perform some actions

_SearchForm (view)

    @using (Html.BeginForm("Search", "Search", FormMethod.Post))
    {
        @Html.TextBox("querySTR")
        <input class="btn btn-primary btn-large" type="submit" value="Search" />
        <label>@Html.RadioButton("rdList", "rdExact") Exact Term</label>
        <label>@Html.RadioButton("rdList", "rdStart", true) Start of Term</label>
        <label>@Html.RadioButton("rdList", "rdPart") Part of Term</label>

    }

Controller

public ActionResult Search(FormCollection collection)
        {

            return RedirectToAction("Index", "Another Controller From where i am now");
        }
tereško
  • 58,060
  • 25
  • 98
  • 150
Hakim
  • 1,242
  • 1
  • 10
  • 22
  • see if this helps...http://stackoverflow.com/questions/18299669/mvc-4-viewmodel-not-being-sent-back-to-controller/18502046#18502046 – foxtrotZulu Nov 21 '13 at 17:35
  • if your going to another area or controller..try this ...http://stackoverflow.com/questions/10785245/redirect-to-action-in-another-controller – foxtrotZulu Nov 21 '13 at 17:49

1 Answers1

1

You can get the controller name in your view this way:

var controllerName = ViewContext.RouteData.Values["Controller"].ToString();

Now you can post the controller name with a hidden field in _SearchForm

@{
    var controllerName = ViewContext.RouteData.Values["Controller"].ToString();
}

@using (Html.BeginForm("Search", "Search", FormMethod.Post))
{
    @Html.TextBox("querySTR")
    <input class="btn btn-primary btn-large" type="submit" value="Search" />
    <label>@Html.RadioButton("rdList", "rdExact") Exact Term</label>
    <label>@Html.RadioButton("rdList", "rdStart", true) Start of Term</label>
    <label>@Html.RadioButton("rdList", "rdPart") Part of Term</label>
    <input type="hidden" name="ControllerName" value="@controllerName" />

}

Then your SearchController can pick it up to redirect to the proper controller

public ActionResult Search(FormCollection collection)
{
    var controllerName = collection["ControllerName"];
    return RedirectToAction("Index", controllerName);
}
Jasen
  • 14,030
  • 3
  • 51
  • 68
  • Is it possible to check for text input length before submitting the form ? i am currently handling this in the controller but i want it not to submit unless longer than 3 chars – Hakim Nov 21 '13 at 21:44
  • You can do that with javascript. Check out jquery validation plugin. The MVC project templates in Visual Studio has this built-in for you. – Jasen Nov 21 '13 at 23:31