c# - 如何在部分页面中设置动态 Controller 名称

标签 c# asp.net-mvc asp.net-mvc-4 razor asp.net-mvc-5

我有一个部分页面,它使用两个不同 Controller 的 View 页面,但有相同的 Edit Action 方法。我需要在运行时为特定页面动态设置 Controller 名称。我该怎么做?

共享文件夹中我的部分页面 _SearchProduct 它仅适用于 WomanController 操作方法 Edit:

<div class="row">
    <div class="col-md-6">
        @using (Html.BeginForm("Edit", "Woman", FormMethod.Get))
        {
            <p>
                Find by Product Id : @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
                <input type="submit" value="Search" />
            </p>
        }
    </div>
    <div class="col-md-6">


        <span style="color:green">@ViewBag.ProductName </span>
    </div>
    <span style="color:red"> @ViewBag.FindResult </span>
</div>

我的 WomanController 编辑页面:

   @model MKL.Models.WomanProduct

<hr />
@Html.Partial("~/Views/Shared/_SearchProduct.cshtml")
<hr />
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.WomanProductId)

        @if (ViewBag.ProductId != null)
        {

            @Html.Hidden("ProductId", (int)ViewBag.ProductId)
        }

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>


    </div>
}

我的 ManController 编辑页面:

      @model MKL.Models.ManProduct

<hr />
@Html.Partial("~/Views/Shared/_SearchProduct.cshtml")
<hr />
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.ManProductProductId)

        @if (ViewBag.ProductId != null)
        {

            @Html.Hidden("ProductId", (int)ViewBag.ProductId)
        }

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>


    </div>
}

因此需要动态设置分部 View Controller 名称 ManWoman

 @using (Html.BeginForm("Edit", "", FormMethod.Get)){}

最佳答案

您可以将模型传递给部分 Controller :

@Html.Partial("~/Views/Shared/_SearchProduct.cshtml", Model)

_SearchProduct.cshtml 中,Model 将是 WomanProductManProduct 类型,具体取决于 View 称为 Partial。然后,根据模型类型选择 Controller :

@{
    var ctrl = Model is WomanProduct ? "Woman" : "Man";
}
@using (Html.BeginForm("Edit", ctrl, FormMethod.Get))

关于c# - 如何在部分页面中设置动态 Controller 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37201364/

相关文章:

C#MVC : Return ViewModel or Model Class?

c# - 如何显示两个表的搜索结果?

javascript - 允许用户设置 HTML 元素 CSS

javascript - 有时只有 IE 11 失去对 ajax 调用的关注 ASP.NET MVC4

c# - 是否可以调用 OpCodes.Jmp 将控制转移到驻留在不同程序集上的方法?

c# - 使用最小起订量抛出异常模拟 IMemoryCache

c# - 读取资源文件时出错c#

asp.net-mvc - 使用Asp.Net C#MVC4和Json,如何使我的图表根据页面数据表进行更新

asp.net-mvc-4 - 在 ASP.NET MVC 中存储用户特定数据

c# - 如何重复for循环迭代c#?