MVC에서 기본 경로 (영역으로)를 설정하는 방법
좋아, 이것은 이전에 요청되었지만 거기에는 확실한 해결책이 없습니다. 따라서 자신과 다른 사람들을 위해이 기능을 유용하게 사용할 수 있습니다.
MVC2 (ASP.NET)에서는 누군가 웹 사이트를 탐색 할 때 기본 영역이 지정되어 있기를 바랍니다. 따라서 내 사이트로 이동하면 AreaZ의 ControllerX ActionY로 보내야합니다.
Global.asax에서 다음 경로 사용
routes.MapRoute(
"Area",
"",
new { area = "AreaZ", controller = "ControllerX ", action = "ActionY " }
);
이제 이것은 올바른 페이지를 제공하려고 시도하는 것처럼 작동합니다. 그러나 MVC는 Area 폴더가 아닌 사이트의 루트에서 View를 찾습니다.
이 문제를 해결할 수있는 방법이 있습니까?
편집하다
'솔루션'이 있으며 ControllerX에 있으며 ActionY는 뷰의 전체 경로를 반환합니다. 해킹 비트이지만 작동합니다. 그러나 더 나은 해결책이 있기를 바랍니다.
public ActionResult ActionY()
{
return View("~/Areas/AreaZ/views/ActionY.aspx");
}
편집하다:
이것은 또한 페이지의 HTML ActionLink가있을 때 문제가됩니다. 영역이 설정되어 있지 않으면 동작 링크가 공백으로 출력됩니다.
이 모든 것이 설계 상 또는 결함입니까?
이것은 나에게 관심이 있었고 마침내 그것을 볼 기회가있었습니다. 다른 사람들은 이것이 라우팅 자체 의 문제가 아니라 관점 을 찾는 데 문제가 있다는 것을 이해 하지 못했을 것입니다. 아마 질문 제목에 라우팅에 관한 것이기 때문일 것입니다.
어쨌든 이것은 뷰 관련 문제이므로 원하는 것을 얻는 유일한 방법 은 기본 뷰 엔진 을 재정의하는 것 입니다. 일반적으로이 작업을 수행 할 때는 뷰 엔진을 간단하게 전환하기위한 것입니다 (예 : Spark, NHaml 등). 이 경우 재정의해야하는 View 생성 논리가 아니라 클래스 의 FindPartialView
및 FindView
메서드입니다 VirtualPathProviderViewEngine
.
다른 모든이 (가)에 있기 때문에,이 방법은 실제로 가상 것을 당신에게 행운의 별을 감사 할 수 VirtualPathProviderViewEngine
조차없는 접근 이 개인, 그리고 그게하게 - 아주 당신이 이미 코드의 기본적으로 재 작성 절반에 있기 때문에 짜증나 찾기 논리를 재정의 위치 캐시 및 위치 형식으로 잘 재생하려면 작성하십시오. Reflector를 파고 들자 마침내 작업 솔루션을 찾았습니다.
내가 여기서 한 일은 먼저 대신에 AreaAwareViewEngine
직접 파생 되는 초록 을 만드는 VirtualPathProviderViewEngine
것입니다 WebFormViewEngine
. 대신 Spark보기를 만들거 나이 클래스를 기본 유형으로 사용할 수 있도록이 작업을 수행했습니다.
아래 코드는 꽤 오래 걸리므로 실제로 수행하는 작업에 대한 간단한 요약을 제공합니다 {2}
. 지역 이름에 해당하는 위치 형식 {1}
을 컨트롤러 이름 과 동일한 방식으로 입력 할 수 있습니다. 그게 다야! 이것이 우리가이 코드를 모두 작성해야하는 것입니다.
BaseAreaAwareViewEngine.cs
public abstract class BaseAreaAwareViewEngine : VirtualPathProviderViewEngine
{
private static readonly string[] EmptyLocations = { };
public override ViewEngineResult FindView(
ControllerContext controllerContext, string viewName,
string masterName, bool useCache)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (string.IsNullOrEmpty(viewName))
{
throw new ArgumentNullException(viewName,
"Value cannot be null or empty.");
}
string area = getArea(controllerContext);
return FindAreaView(controllerContext, area, viewName,
masterName, useCache);
}
public override ViewEngineResult FindPartialView(
ControllerContext controllerContext, string partialViewName,
bool useCache)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (string.IsNullOrEmpty(partialViewName))
{
throw new ArgumentNullException(partialViewName,
"Value cannot be null or empty.");
}
string area = getArea(controllerContext);
return FindAreaPartialView(controllerContext, area,
partialViewName, useCache);
}
protected virtual ViewEngineResult FindAreaView(
ControllerContext controllerContext, string areaName, string viewName,
string masterName, bool useCache)
{
string controllerName =
controllerContext.RouteData.GetRequiredString("controller");
string[] searchedViewPaths;
string viewPath = GetPath(controllerContext, ViewLocationFormats,
"ViewLocationFormats", viewName, controllerName, areaName, "View",
useCache, out searchedViewPaths);
string[] searchedMasterPaths;
string masterPath = GetPath(controllerContext, MasterLocationFormats,
"MasterLocationFormats", masterName, controllerName, areaName,
"Master", useCache, out searchedMasterPaths);
if (!string.IsNullOrEmpty(viewPath) &&
(!string.IsNullOrEmpty(masterPath) ||
string.IsNullOrEmpty(masterName)))
{
return new ViewEngineResult(CreateView(controllerContext, viewPath,
masterPath), this);
}
return new ViewEngineResult(
searchedViewPaths.Union<string>(searchedMasterPaths));
}
protected virtual ViewEngineResult FindAreaPartialView(
ControllerContext controllerContext, string areaName,
string viewName, bool useCache)
{
string controllerName =
controllerContext.RouteData.GetRequiredString("controller");
string[] searchedViewPaths;
string partialViewPath = GetPath(controllerContext,
ViewLocationFormats, "PartialViewLocationFormats", viewName,
controllerName, areaName, "Partial", useCache,
out searchedViewPaths);
if (!string.IsNullOrEmpty(partialViewPath))
{
return new ViewEngineResult(CreatePartialView(controllerContext,
partialViewPath), this);
}
return new ViewEngineResult(searchedViewPaths);
}
protected string CreateCacheKey(string prefix, string name,
string controller, string area)
{
return string.Format(CultureInfo.InvariantCulture,
":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:",
base.GetType().AssemblyQualifiedName,
prefix, name, controller, area);
}
protected string GetPath(ControllerContext controllerContext,
string[] locations, string locationsPropertyName, string name,
string controllerName, string areaName, string cacheKeyPrefix,
bool useCache, out string[] searchedLocations)
{
searchedLocations = EmptyLocations;
if (string.IsNullOrEmpty(name))
{
return string.Empty;
}
if ((locations == null) || (locations.Length == 0))
{
throw new InvalidOperationException(string.Format("The property " +
"'{0}' cannot be null or empty.", locationsPropertyName));
}
bool isSpecificPath = IsSpecificPath(name);
string key = CreateCacheKey(cacheKeyPrefix, name,
isSpecificPath ? string.Empty : controllerName,
isSpecificPath ? string.Empty : areaName);
if (useCache)
{
string viewLocation = ViewLocationCache.GetViewLocation(
controllerContext.HttpContext, key);
if (viewLocation != null)
{
return viewLocation;
}
}
if (!isSpecificPath)
{
return GetPathFromGeneralName(controllerContext, locations, name,
controllerName, areaName, key, ref searchedLocations);
}
return GetPathFromSpecificName(controllerContext, name, key,
ref searchedLocations);
}
protected string GetPathFromGeneralName(ControllerContext controllerContext,
string[] locations, string name, string controllerName,
string areaName, string cacheKey, ref string[] searchedLocations)
{
string virtualPath = string.Empty;
searchedLocations = new string[locations.Length];
for (int i = 0; i < locations.Length; i++)
{
if (string.IsNullOrEmpty(areaName) && locations[i].Contains("{2}"))
{
continue;
}
string testPath = string.Format(CultureInfo.InvariantCulture,
locations[i], name, controllerName, areaName);
if (FileExists(controllerContext, testPath))
{
searchedLocations = EmptyLocations;
virtualPath = testPath;
ViewLocationCache.InsertViewLocation(
controllerContext.HttpContext, cacheKey, virtualPath);
return virtualPath;
}
searchedLocations[i] = testPath;
}
return virtualPath;
}
protected string GetPathFromSpecificName(
ControllerContext controllerContext, string name, string cacheKey,
ref string[] searchedLocations)
{
string virtualPath = name;
if (!FileExists(controllerContext, name))
{
virtualPath = string.Empty;
searchedLocations = new string[] { name };
}
ViewLocationCache.InsertViewLocation(controllerContext.HttpContext,
cacheKey, virtualPath);
return virtualPath;
}
protected string getArea(ControllerContext controllerContext)
{
// First try to get area from a RouteValue override, like one specified in the Defaults arg to a Route.
object areaO;
controllerContext.RouteData.Values.TryGetValue("area", out areaO);
// If not specified, try to get it from the Controller's namespace
if (areaO != null)
return (string)areaO;
string namespa = controllerContext.Controller.GetType().Namespace;
int areaStart = namespa.IndexOf("Areas.");
if (areaStart == -1)
return null;
areaStart += 6;
int areaEnd = namespa.IndexOf('.', areaStart + 1);
string area = namespa.Substring(areaStart, areaEnd - areaStart);
return area;
}
protected static bool IsSpecificPath(string name)
{
char ch = name[0];
if (ch != '~')
{
return (ch == '/');
}
return true;
}
}
지금까지 언급했듯이 이것은 구체적인 엔진이 아니므로이를 생성해야합니다. 다행스럽게도이 부분은 훨씬 쉽습니다. 기본 형식을 설정하고 실제로보기를 만드는 것만으로도 충분 합니다.
AreaAwareViewEngine.cs
public class AreaAwareViewEngine : BaseAreaAwareViewEngine
{
public AreaAwareViewEngine()
{
MasterLocationFormats = new string[]
{
"~/Areas/{2}/Views/{1}/{0}.master",
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.master",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Views/{1}/{0}.master",
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.master"
"~/Views/Shared/{0}.cshtml"
};
ViewLocationFormats = new string[]
{
"~/Areas/{2}/Views/{1}/{0}.aspx",
"~/Areas/{2}/Views/{1}/{0}.ascx",
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.aspx",
"~/Areas/{2}/Views/Shared/{0}.ascx",
"~/Areas/{2}/Views/Shared/{0}.cshtml",
"~/Views/{1}/{0}.aspx",
"~/Views/{1}/{0}.ascx",
"~/Views/{1}/{0}.cshtml",
"~/Views/Shared/{0}.aspx"
"~/Views/Shared/{0}.ascx"
"~/Views/Shared/{0}.cshtml"
};
PartialViewLocationFormats = ViewLocationFormats;
}
protected override IView CreatePartialView(
ControllerContext controllerContext, string partialPath)
{
if (partialPath.EndsWith(".cshtml"))
return new System.Web.Mvc.RazorView(controllerContext, partialPath, null, false, null);
else
return new WebFormView(controllerContext, partialPath);
}
protected override IView CreateView(ControllerContext controllerContext,
string viewPath, string masterPath)
{
if (viewPath.EndsWith(".cshtml"))
return new RazorView(controllerContext, viewPath, masterPath, false, null);
else
return new WebFormView(controllerContext, viewPath, masterPath);
}
}
standard에 몇 개의 항목을 추가했습니다 ViewLocationFormats
. 이들은 새로운 {2}
이 항목 {2}
받는 사람 매핑됩니다 area
우리는에 넣어 RouteData
. 나는 MasterLocationFormats
혼자 떠났지만, 원한다면 분명히 바꿀 수 있습니다.
이제이 global.asax
뷰 엔진을 등록 하도록 수정하십시오 :
Global.asax.cs
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new AreaAwareViewEngine());
}
... 기본 경로를 등록하십시오.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Area",
"",
new { area = "AreaZ", controller = "Default", action = "ActionY" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
이제 AreaController
방금 참조한 것을 작성하십시오 .
DefaultController.cs (~ / Controllers /)
public class DefaultController : Controller
{
public ActionResult ActionY()
{
return View("TestView");
}
}
분명히 우리는 디렉토리 구조와 함께 볼 필요가 있습니다-우리는 이것을 매우 간단하게 유지할 것입니다 :
TestView.aspx (~ / Areas / AreaZ / Views / Default / 또는 ~ / Areas / AreaZ / Views / Shared /)
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<h2>TestView</h2>
This is a test view in AreaZ.
그리고 그게 다야. 마지막으로 완료되었습니다 .
대부분의 경우, 당신은 단지를 취할 수 있어야 BaseAreaAwareViewEngine
하고 AreaAwareViewEngine
그것이이 끝내야 코드를 많이했다 순간에도, 어떤 MVC 프로젝트에 드롭, 당신은 한 번만 작성해야합니다. 그 후에는 몇 줄을 편집하고 global.asax.cs
사이트 구조를 만드는 것입니다.
이것이 내가 한 방법입니다. MapRoute ()를 사용하여 영역을 설정할 수없는 이유는 모르지만 경로 개체를 반환하므로 원하는 추가 변경을 계속 수행 할 수 있습니다. 엔터프라이즈 고객에게 판매되는 모듈 식 MVC 사이트가 있고 dll을 bin 폴더에 드롭하여 새 모듈을 추가 할 수 있어야하기 때문에 이것을 사용합니다. AppSettings 구성에서 "HomeArea"를 변경할 수 있습니다.
var route = routes.MapRoute(
"Home_Default",
"",
new {controller = "Home", action = "index" },
new[] { "IPC.Web.Core.Controllers" }
);
route.DataTokens["area"] = area;
편집 : 사용자가 기본적으로 원하는 영역에 대해 AreaRegistration.RegisterArea 에서이 작업을 시도 할 수 있습니다. 나는 그것을 테스트하지 않았지만 AreaRegistrationContext.MapRoute가 route.DataTokens["area"] = this.AreaName;
당신을 위해 세트 를한다.
context.MapRoute(
"Home_Default",
"",
new {controller = "Home", action = "index" },
new[] { "IPC.Web.Core.Controllers" }
);
심지어 이미 답변을 받았습니다-이것은 짧은 구문입니다 (ASP.net 3, 4, 5).
routes.MapRoute("redirect all other requests", "{*url}",
new {
controller = "UnderConstruction",
action = "Index"
}).DataTokens = new RouteValueDictionary(new { area = "Shop" });
뷰를 찾는 것에 대해 지적한 Aaron에게 감사의 말을 전합니다.
[업데이트] 방금 코드 나 조회 경로를 엉망으로 만들지 않고 사용자를 기본값으로 Area로 보내는 프로젝트를 만들었습니다.
global.asax에서 평소와 같이 등록하십시오.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = ""} // Parameter defaults,
);
}
에서 Application_Start()
다음 순서를 사용해야합니다.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
당신은 지역 등록에 사용
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"ShopArea_default",
"{controller}/{action}/{id}",
new { action = "Index", id = "", controller = "MyRoute" },
new { controller = "MyRoute" }
);
}
예는 http://www.emphess.net/2010/01/31/areas-routes-and-defaults-in-mvc-2-rc/ 에서 찾을 수 있습니다 .
나는 이것이 당신이 요구 한 것이기를 바랍니다.
////
ViewEngine
이 경우 의사를 쓰는 것이 최선의 해결책 이라고 생각하지 않습니다 . (평판이 없기 때문에 댓글을 달 수 없습니다). 는 WebFormsViewEngine
지역 인식하고 포함 AreaViewLocationFormats
으로, 기본적으로 정의된다
AreaViewLocationFormats = new[] {
"~/Areas/{2}/Views/{1}/{0}.aspx",
"~/Areas/{2}/Views/{1}/{0}.ascx",
"~/Areas/{2}/Views/Shared/{0}.aspx",
"~/Areas/{2}/Views/Shared/{0}.ascx",
};
나는 당신이이 협약을 준수하지 않는다고 생각합니다. 당신은 게시
public ActionResult ActionY()
{
return View("~/Areas/AreaZ/views/ActionY.aspx");
}
작동하는 해킹으로, 그러나 그것은
return View("~/Areas/AreaZ/views/ControllerX/ActionY.aspx");
그러나 규칙을 따르지 않으려면 WebFormViewEngine
생성자에서 조회 경로를 설정할 수있는 위치 (예 : MvcContrib에서 수행)에서 파생하거나 짧은 경로를 사용 하면됩니다. little hacky-에 다음과 같은 규칙을 지정하여 Application_Start
:
((VirtualPathProviderViewEngine)ViewEngines.Engines[0]).AreaViewLocationFormats = ...;
물론 이것은 조금 더주의해서 수행해야하지만 아이디어를 보여줍니다. 이 필드는 다음 public
에서 VirtualPathProviderViewEngine
MVC 2 RC에.
사용자 ~/AreaZ
가 ~/
URL 을 방문한 후 URL 로 리디렉션되도록하려고합니다 . 귀하의 루트 내에서 다음 코드를 사용하여 달성합니다 HomeController
.
public class HomeController
{
public ActionResult Index()
{
return RedirectToAction("ActionY", "ControllerX", new { Area = "AreaZ" });
}
}
에서 다음 경로 Global.asax
.
routes.MapRoute(
"Redirection to AreaZ",
String.Empty,
new { controller = "Home ", action = "Index" }
);
먼저, 어떤 버전의 MVC2를 사용하고 있습니까? preview2에서 RC로 크게 변경되었습니다.
RC를 사용한다고 가정하면 경로 매핑이 다르게 보일 것입니다. 에서 AreaRegistration.cs
귀하의 지역에서, 당신은 기본 경로, 예를 들어, 어떤 종류를 등록 할 수 있습니다
context.MapRoute(
"ShopArea_default",
"{controller}/{action}/{id}",
new { action = "Index", id = "", controller="MyRoute" }
);
위의 코드는 사용자를 보내드립니다 MyRouteController
우리의 ShopArea
당 기본.
컨트롤러를 지정해야하므로 빈 문자열을 두 번째 매개 변수로 사용하면 예외가 발생합니다.
물론 기본 경로를 변경해야 Global.asax
합니다. 예를 들어 기본 사이트의 접두사를 사용하여이 기본 경로를 방해하지 않습니다.
이 글과 Haack의 답변 참조 : MVC 2 AreaRegistration Routes Order
도움이 되었기를 바랍니다.
RC 에이 설정이 있는지 확실하지 않지만 Application_Start에 다음을 추가하면 효과가 있습니다.
var engine = (WebFormViewEngine)ViewEngines.Engines.First();
// These additions allow me to route default requests for "/" to the home area
engine.ViewLocationFormats = new string[] {
"~/Views/{1}/{0}.aspx",
"~/Views/{1}/{0}.ascx",
"~/Areas/{1}/Views/{1}/{0}.aspx", // new
"~/Areas/{1}/Views/{1}/{0}.ascx", // new
"~/Areas/{1}/Views/{0}.aspx", // new
"~/Areas/{1}/Views/{0}.ascx", // new
"~/Views/{1}/{0}.ascx",
"~/Views/Shared/{0}.aspx",
"~/Views/Shared/{0}.ascx"
};
이 작업을 수행하기 위해 수행 한 작업은 다음과 같습니다.
- root / Controllers 폴더에 기본 컨트롤러를 만들었습니다. 컨트롤러 이름을 DefaultController로 지정했습니다.
컨트롤러에서 다음 코드를 추가했습니다.
namespace MyNameSpace.Controllers { public class DefaultController : Controller { // GET: Default public ActionResult Index() { return RedirectToAction("Index", "ControllerName", new {area = "FolderName"}); } } }
내 RouterConfig.cs에서 다음을 추가했습니다.
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new {controller = "Default", action = "Index", id = UrlParameter.Optional});
이 모든 것의 비결은 앱을 시작할 때마다 항상 시작 컨트롤러가되는 기본 생성자를 만든 것입니다. 기본 컨트롤러에 도달하면 기본 인덱스 작업에서 지정한 컨트롤러로 리디렉션됩니다. 내 경우에는
www.myurl.com/FolderName/ControllerName
.
routes.MapRoute(
"Area",
"{area}/",
new { area = "AreaZ", controller = "ControlerX ", action = "ActionY " }
);
당신은 그것을 시도 했습니까?
다른 빌딩 블록 찾기는 요청 수명주기에서 수행됩니다. ASP.NET MVC 요청 수명주기의 첫 번째 단계 중 하나는 요청 된 URL을 올바른 컨트롤러 작업 방법에 매핑하는 것입니다. 이 프로세스를 라우팅이라고합니다. 기본 경로는 Global.asax 파일에서 초기화되며 요청을 처리하는 방법을 ASP.NET MVC 프레임 워크에 설명합니다. MvcApplication1 프로젝트에서 Global.asax 파일을 두 번 클릭하면 다음 코드가 표시됩니다.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing;
namespace MvcApplication1 {
public class GlobalApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
}
응용 프로그램이 컴파일되거나 웹 서버가 다시 시작될 때마다 발생하는 Application_Start () 이벤트 핸들러에서 경로 테이블이 등록됩니다. 기본 경로의 이름은 Default이며 http://www.example.com/ {controller} / {action} / {id} 형식의 URL에 응답합니다 . {와} 사이의 변수는 요청 URL의 실제 값으로 채워지거나 URL에 대체가없는 경우 기본값으로 채워집니다. 이 기본 경로는 기본 라우팅 매개 변수에 따라 홈 컨트롤러 및 색인 조치 방법에 맵핑됩니다. 이 라우팅 맵에 대한 다른 조치는 없습니다.
기본적으로 가능한 모든 URL을이 기본 경로를 통해 매핑 할 수 있습니다. 우리 자신의 경로를 만들 수도 있습니다. 예를 들어 URL http://www.example.com/Employee/Maarten 을 Employee 컨트롤러, Show 작업 및 firstname 매개 변수에 매핑합니다 . 방금 연 Global.asax 파일에 다음 코드 스 니펫을 삽입 할 수 있습니다. ASP.NET MVC 프레임 워크는 첫 번째 일치하는 경로를 사용하므로이 코드 스 니펫은 기본 경로 위에 삽입되어야합니다. 그렇지 않으면 경로가 사용되지 않습니다.
routes.MapRoute(
"EmployeeShow", // Route name
"Employee/{firstname}", // URL with parameters
new { // Parameter defaults
controller = "Employee",
action = "Show",
firstname = ""
}
);
이제이 라우트에 필요한 구성 요소를 추가하겠습니다. 우선 Controllers 폴더에 EmployeeController라는 클래스를 만듭니다. 프로젝트에 새 항목을 추가하고 웹 | 웹 | 아래에있는 MVC 컨트롤러 클래스 템플리트를 선택하여이를 수행 할 수 있습니다. MVC 카테고리. 색인 조치 메소드를 제거하고 이름이 Show 인 메소드 또는 조치로 바꾸십시오. 이 메소드는 이름 매개 변수를 승인하고 ViewData 사전에 데이터를 전달합니다. 이 사전은 뷰에서 데이터를 표시하는 데 사용됩니다.
EmployeeController 클래스는 Employee 객체를 뷰에 전달합니다. 이 Employee 클래스는 Models 폴더에 추가해야합니다 (이 폴더를 마우스 오른쪽 단추로 클릭 한 다음 상황에 맞는 메뉴에서 클래스 추가를 선택하십시오). Employee 클래스의 코드는 다음과 같습니다.
namespace MvcApplication1.Models {
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
}
사용자 정의보기 엔진을 만들면이 작업을 수행 할 수 있지만 여전히 대안을 가질 수 있습니다.
- 기본적으로 표시 할 내용을 결정하십시오.
- 컨트롤러와 액션 (및 영역)이있는 것이 맞습니까?
- 해당 지역 등록을 열고 다음과 같이 추가하십시오.
public override void RegisterArea(AreaRegistrationContext context) { //this makes it work for the empty url (just domain) to act as current Area. context.MapRoute( "Area_empty", "", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new string[] { "Area controller namespace" } ); //other routes of the area }
건배!
이 질문에 대한 해결책은 사용자 정의보기 엔진을 만드는 방법을 요약하면 정확하지만 질문에 올바르게 대답하지 않는 것입니다. 여기서 문제는 Pino가 기본 경로를 잘못 지정했다는 것 입니다. 특히 그의 "영역"정의가 잘못되었습니다. "Area"는 DataTokens 컬렉션을 통해 확인되며 다음과 같이 추가해야합니다.
var defaultRoute = new Route("",new RouteValueDictionary(){{"controller","Default"},{"action","Index"}},null/*constraints*/,new RouteValueDictionary(){{"area","Admin"}},new MvcRouteHandler());
defaultRoute.DataTokens.Add("Namespaces","MyProject.Web.Admin.Controller");
routes.Add(defaultRoute);
defaults 객체에서 지정된 "area"는 무시 됩니다. 위의 코드는 기본 루트를 생성하여 사이트 루트에 대한 요청을 포착 한 다음 기본 컨트롤러, 관리 영역의 인덱스 작업을 호출합니다. DataToken에 "네임 스페이스"키가 추가됨에 유의하십시오. 이름이 같은 컨트롤러가 여러 개인 경우에만 필요합니다. 이 솔루션은 Mvc2 및 Mvc3 .NET 3.5 / 4.0에서 검증되었습니다.
음,이 모든 프로그래밍이 왜 필요한지 모르겠습니다.이 기본 경로를 지정하여 원래 문제를 쉽게 해결할 수 있다고 생각합니다 ...
routes.MapRoute("Default", "{*id}",
new { controller = "Home"
, action = "Index"
, id = UrlParameter.Optional
}
);
참고 URL : https://stackoverflow.com/questions/2140208/how-to-set-a-default-route-to-an-area-in-mvc
'Programing' 카테고리의 다른 글
asp.net에서 List <>를 List <>에 추가하는 방법 (0) | 2020.07.15 |
---|---|
LocalDate를 문자열로 포맷하는 방법은 무엇입니까? (0) | 2020.07.15 |
문서 디렉토리 (NSDocumentDirectory)는 무엇입니까? (0) | 2020.07.15 |
모키 토 : InvalidUseOfMatchersException (0) | 2020.07.15 |
불투명도 : 0은 가시성 : 숨김과 효과가 동일합니다. (0) | 2020.07.15 |