如何在MVC 4 Web应用程序中更改默认视图

时间:2017-05-16 17:09:35

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

默认情况下,Visual Studio 2017中的MVC 4将fileObj.getAbsolutePath();设置为所有页面的默认布局。我相信它是在_Layout.cshtml中执行此操作:

App_Start/RouteConfig.cs

(索引设置为主页)

enter image description here

我仍然不确定索引是如何获得routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 的。但是,如果我试图设置一个不同的视图 - 登录页面 - 作为主页,如此?

enter image description here

此外,我正在尝试删除标题中的报告,帐户,设置和注销_Layout.cshtml,以便页面与上面的设计相匹配。我还需要一个内部带有表单的容器。

我尝试在<li>'s_Login内创建/Home视图,并在/Shared中将"Index"更改为"Login"

App_Start/RouteConfig.cs

enter image description here

但那给了我一个错误:

enter image description here

如何创建视图并将该视图设置为此MVC 4 Web App的默认视图?感谢

2 个答案:

答案 0 :(得分:3)

您在默认参数中看到的内容为action是控制器方法的名称,而不是视图,因此您应该在{{{{}}中创建一个名为Login的方法1}}控制器并为其创建关联的视图(在Home方法中右键单击并选择添加视图)。然后它将作为默认主页。

Login

所以你的defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional } 控制器看起来像这样:

Home

此外,如果您不希望在“登录”页面中使用默认布局,则可以在“登录”页面顶部添加此布局

public class HomeController : Controller
{
    public IActionResult Login()
    {
        return View();
    }
    //other codes   
 }

答案 1 :(得分:2)

您看到的错误似乎不是因为布局页面。

此错误是因为Home控制器中缺少登录操作。

您会看到,指定的默认值为Controlller="Home", Action="Login" 即编译器在Home控制器中查找Login操作。当它找不到时,就会抛出这个错误!

你可以通过添加登录操作来消除它:

public ActionResult Login(string Uname, string Password)
{
    return View();
}

在家庭控制器中!这就是问题中的错误。

以下是您的问题的解决方案。 您可以通过添加如下所示的剃刀代码为每个视图添加不同的布局,以指定视图的布局。

@{
   Layout = "~/Views/Shared/_Layout.cshtml";
                  //This is the path to the layout. You could change this to your custom layout's path.
}

希望这有帮助!