简体   繁体   中英

partial view with controller MVC c#

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 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM