English 中文(简体)
每个视图都有公共方法?ASP.MVC中的默认ActionResult和路由。
原标题:
  • 时间:2009-03-22 20:22:35
  •  标签:

我正在尝试使用ASP.NET MVC和路由。

似乎MVC强制我在每次想要创建视图时向控制器添加一个公共方法。例如:

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

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

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

我不想为每个视图创建公共方法。默认情况下,我希望所有视图在系统中的行为为“返回视图()”,除非另有指定。

例如,HTTP GET:

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 POST上的联系我们页面,请访问:

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()
   }

}

Thanks, Brian

最佳回答

使用ShowBasicView从您的编辑中可能存在的潜在问题是,由于视图的隐式连线,每个URL都将返回相同的视图,即:

视图首页展示基本视图.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);
  }
}

您可能还需要添加一个基本URL的路由,因为ShowBasic路由仅会对带有字符串值的URL起作用。

问题回答

你可以在你的控制器中添加以下方法,它

protected override void HandleUnknownAction(string actionName)
{
    try{
       this.View(actionName).ExecuteResult(this.ControllerContext);
    }catch(Exception ex){
       // log exception...
       base.HandleUnknownAction(actionName);
    }
}




相关问题
热门标签