是否可以为同一个网址使用两个不同的控制器?
这是必需的,因为我需要URL始终保持不变,但它应该使用不同的控制器。我的控制器(Apples
,Bananas
等)和视图被分成每个项目。
我需要在我的主要MVC项目中执行一项操作,以根据某些逻辑从Bananas
或Apples
项目返回操作/视图。
那么我将如何继续使用相同的url但从不同的控制器返回操作/视图?
我正在使用MVC 4
答案 0 :(得分:0)
您的网址应该是选择控制器的逻辑所在。也许您需要重新组织项目以拥有一个控制器并将其他逻辑放在控制器操作中以填充模型?
但是,如果您坚持使用此路由,则可能需要覆盖CreateController
中的DefaultControllerFactory
,这是实例化控制器的类,通常基于您的控制器名称。以下是我的一个项目中的示例:
public class ErrorHandlingControllerFactory : DefaultControllerFactory
{
/// <summary>
/// Injects a custom attribute
/// on every action that is invoked by the controller
/// </summary>
/// <param name="requestContext">The request context</param>
/// <param name="controllerName">The name of the controller</param>
/// <returns>An instance of a controller</returns>
public override IController CreateController(
RequestContext requestContext,
string controllerName)
{
var controller =
base.CreateController(requestContext,
controllerName);
var c = controller as Controller;
if (c != null)
{
c.ActionInvoker =
new ErrorHandlingActionInvoker(
new HandleErrorWithELMAHAttribute());
}
return controller;
}
}
您需要设置路由以传递已知的控制器名称(可怕的魔术字符串......),测试此控制器名称,如果检测到运行您的逻辑以获取实际的控制器名称并将其传递给{ {1}}。
答案 1 :(得分:0)
我写了这些代码。我希望它对你有所帮助。我使用隐藏字段来了解将运行哪种方法。
这些是我的模特:
namespace MvcSameController.Models
{
public class RouteModel
{
public SampleModel1 SampleModel1 { get; set; }
public SampleModel2 SampleModel2 { get; set; }
}
public class SampleModel1
{
public int Id { get; set; }
public string Name { get; set; }
}
public class SampleModel2
{
public int Id { get; set; }
public string Surname { get; set; }
}
}
这是控制器:
using System.Web.Mvc;
using MvcSameController.Models;
namespace MvcSameController.Controllers
{
public class SameController : Controller
{
//
// GET: /Same/
public ActionResult Index()
{
return View();
}
[HttpPost]
public void Index(RouteModel routeModel, string type)
{
if (type == "1")
{
//Code for type 1
}
else if (type == "2")
{
//Code for type 2
}
}
}
}
并查看:
@{
ViewBag.Title = "Index";
}
@model MvcSameController.Models.RouteModel
<section id="loginForm">
<h2>Type1 </h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.Hidden("type",1)
<fieldset>
<legend>Type1 Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.SampleModel1.Name)
@Html.TextBoxFor(m => m.SampleModel1.Name)
@Html.ValidationMessageFor(m => m.SampleModel1.Name)
</li>
</ol>
<input type="submit" value="Run Method1" />
</fieldset>
}
</section>
<section id="loginForm">
<h2>Type2</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.Hidden("type",2)
<fieldset>
<legend>Type2 Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.SampleModel2.Surname)
@Html.TextBoxFor(m => m.SampleModel2.Surname)
@Html.ValidationMessageFor(m => m.SampleModel2.Surname)
</li>
</ol>
<input type="submit" value="Run Method2" />
</fieldset>
}
</section>
您可以从here
下载我的样本