【问题标题】:partial view with controller MVC c#带有控制器 MVC c# 的部分视图
【发布时间】:2013-11-21 17:21:21
【问题描述】:

嗨,我有一个包含搜索表单的部分视图,搜索表单重定向到控制器“搜索”中的操作“搜索”。 我在多个位置使用此表单,但我需要控制器“搜索”中的操作“搜索”来获取此表单用于执行某些操作的位置

_SearchForm(查看)

    @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>

    }

控制器

public ActionResult Search(FormCollection 集合)
        {

            return RedirectToAction("Index", "我现在所在的另一个控制器");
        }

【问题讨论】:

标签: c# asp.net-mvc


【解决方案1】:

您可以通过这种方式在视图中获取控制器名称:

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

现在您可以在 _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" />

}

然后您的SearchController 可以将其拾取并重定向到正确的控制器

public ActionResult Search(FormCollection collection)
{
    var controllerName = collection["ControllerName"];
    return RedirectToAction("Index", controllerName);
}

【讨论】:

  • 是否可以在提交表单之前检查文本输入长度?我目前正在控制器中处理此问题,但我希望它不提交,除非超过 3 个字符
  • 你可以用 javascript 做到这一点。查看 jquery 验证插件。 Visual Studio 中的 MVC 项目模板为您提供了此内置功能。
猜你喜欢
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 2016-01-24
  • 2017-04-14
相关资源
最近更新 更多