对每个视图公共方法?默认的ActionResult和ASP.MVC路线
-
21-08-2019 - |
题
我尝试用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()
在所有结果 “返回查看()”。这是我的问题,我试图消除创建简单的观点公开的操作方法。
对于需要额外的处理的观点,如联系我们页面上的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()
}
}
谢谢, 布赖恩
解决方案
与具有从编辑ShowBasicView潜在的问题是,由于视图的隐式布线,每个这些网址将所有返回相同的视图,即:
\视图\主页\ 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);
}
}
您将可能还需要添加路由的基本URL,因为ShowBasic路由只命中一个字符串值的URL。
其他提示
您可以在控制器添加下面的方法,它
protected override void HandleUnknownAction(string actionName)
{
try{
this.View(actionName).ExecuteResult(this.ControllerContext);
}catch(Exception ex){
// log exception...
base.HandleUnknownAction(actionName);
}
}
不隶属于 StackOverflow