문제

ASP.NET MVC 및 경로를 실험하고 있습니다.

MVC는보기를 만들고 싶을 때마다 컨트롤러에 공개 메소드를 추가하도록 강요합니다. 예를 들어:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    //... a public method for every view.. :(
}

나는 모든 견해에 대한 공개 방법을 만들고 싶지 않습니다. 기본적으로 달리 지정되지 않는 한 시스템의 모든 뷰에 대해 "return view ()"의 동작을 원합니다.

예를 들어, HTTP는 다음과 같습니다.

site.com/about
site.com/features
site.com/
site.com/testimonials
site.com/contact-us

지금은 다음을 추가해야 할 것입니다.

HomeController.About()
HomeController.Features()
HomeController.Index()
HomeController.Testimonials()
HomeController.ContactUs()

모든 결과 "return view ()"가 발생합니다. 이것은 나의 문제입니다. 나는 간단한 견해를위한 공개 행동 방법을 만들려고 노력하고 있습니다.

HTTP 게시물의 문의 페이지와 같이 추가 처리가 필요한 뷰의 경우 :

site.com/contact-us

SMTP 메시지를 보내기 위해 컨트롤러에 메소드를 특별히 추가하고 싶습니다.


다음은 내가하려는 일에 대한보다 간결한 예입니다.

public class HomeController{

   public ActionResult ShowBasicView(){
     //HTTP GET:
     //site.com/about
     //site.com/features
     //site.com/
     //site.com/testimonials

     //All URLs above map to this action

     return View();
   }

   [AcceptVerbs(HttpVerbs.Post)]
   public ActionResult ContactUs(FormCollection data){

     //HTTP POST:
     //site.com/contact-us

     //POST URL maps here.

     SmtpClient.Send(new MailMessage()) //etc...
     return View()
   }

}

고마워요, 브라이언

도움이 되었습니까?

해결책

편집에서 ShowBasicView를 사용하는 데있어 잠재적 인 문제는 뷰의 암시 적 배선으로 인해 각 URL이 모두 동일한 뷰를 반환한다는 것입니다.

views home showbasicview.aspx

이제는 아마도 아마도 당신이 원하는 것일 수 있습니다.

다음과 같은 경로를 사용하여이를 설정할 수 있습니다.

routes.MapRoute(  
  "ShowBasic",
  "{id}",
  new { controller = "Home", action = "ShowBasicView", id = "home" }
);

컨트롤러를 다음과 같이 수정하십시오.

public class HomeController: Controller{

  public ActionResult ShowBasicView(string pageName){
    // Do something here to get the page data from the Model, 
    // and pass it into the ViewData
    ViewData.Model = GetContent(pageName);

    // All URLs above map to this action
    return View();
  }
}

또는 컨텐츠가 뷰에서 하드 코딩 된 경우 시도 할 수 있습니다.

public class HomeController: Controller{

  public ActionResult ShowBasicView(string pageName){
    // All URLs above map to this action
    // Pass the page name to the view method to call that view.        
    return View(pageName);
  }
}

Showbasic Route는 문자열 값의 URL에만 적용되므로 기본 URL에 대한 경로를 추가해야 할 수도 있습니다.

다른 팁

컨트롤러에 다음 방법을 추가 할 수 있습니다.

protected override void HandleUnknownAction(string actionName)
{
    try{
       this.View(actionName).ExecuteResult(this.ControllerContext);
    }catch(Exception ex){
       // log exception...
       base.HandleUnknownAction(actionName);
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top