Skip to main content
 首页 » 编程设计

c#之MVC之我可以通过 2 个不同的 Controller 在 1 个 View 上显示标题和消息吗

2024年02月13日14haluo1

我是 MVC 的新手,也是 Stackoverflow 的新手。我没有使用任何数据库,但我只想通过 2 个不同的 Controller 在 1 个 View 上显示标题和按摩。我想在我的 Index.cshtml 文件中显示来自 HomeController.cs 文件的 @ViewBag.Title 和来自 OtherController.cs 的 @ViewBag.Massage 显示> 文件。我该怎么做以及如何将 OtherController.cs 引用或附加到 Index.cshtml?请不要告诉我,我是在询问如何将样式表附加到 html 之类的问题,但 MVC 无法做到这一点。

如果真的不可能,那么请告诉我如何使用 _Layout.cshtml 文件通过局部 View 来做到这一点。因为我不想在我的 View 文件中写太多。

提前致谢!

RouteConfig.cs

routes.MapRoute( 
                name: "Default", 
                url: "{controller}/{action}/{id}", 
                defaults: new { controller = "Home", 
                                action = "Index", 
                                id = UrlParameter.Optional 
                              } 
               ); 

HomeController.cs

public ActionResult Index() 
        { 
            ViewBag.Title = ""; 
            return View(); 
        } 

OtherController.cs

public ActionResult Index() 
        { 
            ViewBag.Massage = ""; 
            return View(); 
        } 

Index.cshtml

<title>@ViewBag.Title</title> 
 
<p>@ViewBag.Massage</p> 

请您参考如下方法:

索引操作方法在主 Controller 中是相同的,但在其他 Controller 中你应该返回部分 View 。

   public ActionResult PartialIndex() 
    { 
        ViewBag.Massage = "Message from Partial View"; 
        return PartialView(); 
    } 

局部 View

 <p>@ViewBag.Massage</p> 

在主视图中你可以调用它。

  <h1>@ViewBag.Title.</h1> 
  <h2>@{Html.RenderAction("IndexPartial");}</h2>