代码之家  ›  专栏  ›  技术社区  ›  user3902826

显示mvc2视图

  •  0
  • user3902826  · 技术社区  · 10 年前

    我在aspmvc2应用程序中制作控制器。之后,我为这个控制器创建视图。

    我将此控制器命名为“DisplayName” 然后写一些类似的内容:

    public class DisplayName : Controller
    {
        //
        // GET: /DisplayName/
    
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult DisplaySomething()
        {
            MojaKlasa objCustomer = new MojaKlasa();
            objCustomer.ime = "Random ime";
            objCustomer.broj = 10;
    
            return View("DisplaySomething", objCustomer);
        }
    }
    

    但当我尝试在web浏览器中显示它并调用:

    http://localhost:xxxxx/DisplayName/DisplaySomething
    

    我收到错误:

    Server Error in '/' Application. The resource cannot be found.
    

    我试图找到错误,然后在DisplayNameController中看到一个示例并重命名控制器

    现在我有了:

    public class DisplayNameController : Controller
    {
        //
        // GET: /DisplayName/
    
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult DisplaySomething()
        {
            MojaKlasa objCustomer = new MojaKlasa();
            objCustomer.ime = "Random ime";
            objCustomer.broj = 10;
    
            return View("DisplaySomething", objCustomer);
        }
    }
    

    现在,当我打电话:

    http://localhost:xxxxx/DisplayName/DisplaySomething
    

    应用程序运行完美。

    我接下来的问题是:这是否意味着每个控制器都需要有“控制器”的名称?为什么我不能用我想要的名字?

    Thanx公司

    2 回复  |  直到 10 年前
        1
  •  0
  •   Community Egal    7 年前

    是的,默认情况下应遵循此约定。以下是来自 MSDN :

    所有控制器类必须使用“controller”后缀命名。

    但是,如果您真的想,可以重新定义此命名约定。为此,您必须创建自己的ControllerFactory类,该类负责控制器实例化。可以找到这样的例子 here .

        2
  •  0
  •   Coding Flow    10 年前

    是的,MVC中的默认路由使用基于约定的路由,命名约定是在控制器名称后加上“controller”。