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");
        }
2

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

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
You can do that with javascript. Check out jquery validation plugin. The MVC project templates in Visual Studio has this built-in for you.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.