2014-02-25 4 views
2

MVC 액션 이름과 관련된 모든 마법 문자열을 없애기 위해 만든 다음 코드가 있습니다. 잠재적으로 개발자는 액세스 뮤 테이터를 변경하여 페이지에서도 액세스 할 수 있습니다.상수 문자열로 MVC 작업 이름을?

private const string IndexAction = "Index"; 
public ActionResult Index(){ 
    //do stuff 
} 
public ActionResult Other(){ 
    // do stuff 
    if(foo) 
     return RedirectToAction(IndexAction); 
    //don't foo 
} 

나는 그것이 좋은 생각이 아니라고과 내가 이것을 시도하는 최초의 사람이다 의심 프로그래밍의 세계에 날 리드이 어느 곳을 본 적이 없다. 질문 : 작업의 이름을 올리면 MVC의 교장이 깨집니다.

답변

3

기본적으로 상수를 사용하는 것이 좋습니다 (내 경험에 비추어 볼 때 MVC에서는 흔하지 않지만 컨트롤러가 작 으면 필요하지 않을 수도 있음). 당신이 제안하는 방법에 따라 잠재적으로 몇 가지에서 2 가지로 변경해야하는 부분의 수를 줄입니다.

한 자리로 줄이려면 ActionName 속성을 사용하여 상수를 사용하여 작업의 이름을 지정할 수도 있습니다. 이 시스템을 이해하는 MVC에서 사용하기 때문에 다른 사람들이 더 오래 걸릴 수 있습니다 규칙을 파괴하지만, 한 자리에 변경 제한 할 수있는 장점이있다 다음 ActionName 속성과 그 용도에 대한 자세한 내용은

private const string IndexAction = "Index"; 

[ActionName(IndexAction)] 
public ActionResult Index(){ 
    //do stuff 
} 
public ActionResult Other(){ 
    // do stuff 
    if(foo) 
     return RedirectToAction(IndexAction); 
    //don't foo 
} 

를 참조하십시오 이 question과 그 대답. 때로는 무엇을

1

은과 같이 주어진 컨트롤러 에서 액션 이름을 열거를 만드는 것입니다 :

public class HomeController : Controller 
{ 

    public enum Actions 
    { 
     Index, 
     About, 
     Contact, 
     Hosting, 
     Hartware 
    } 

을 난에 확장 방법을 만들고 싶습니다 원래 클래스와 동일한 네임 스페이스를 사용 연장, 내 페이지의 상단에있는이 경우 "HomeController"에 도착하여 추가이 경우에 나는 System.Web.Mvc를 사용하는 것이 내 면도기 ViewPage에

namespace System.Web.Mvc 
{ 
    public static class MvcExtentions 
    { 
     /// <summary> 
     /// Generates a fully qualified URL to an action method by using the specified action Name. 
     /// </summary> 
     /// <param name="sender">used for the generate the logic</param> 
     /// <param name="actionName">an enum that will be used to generate the name from</param> 
     /// <returns>a fully qualified url to the action in the current controller</returns> 
     public static string Action(this UrlHelper sender, Enum actionName) 
     { 
      return sender.Action(actionName.ToString()); 
     } 
    } 
} 

다음 클래스를 생성 여기서 ByteStream은 내 proj의 이름입니다. 요법

@using ByteStream.Web.Controllers 
@{ 
    ViewData["Title"] = "Home Page"; 
} 

링크를 생성하려면 그때 사용

<a class="btn btn-default btn-default" ref="@Url.Action(HomeController.Actions.Hosting))"> 
Learn More 
</a> 
관련 문제