【问题标题】:.Net MVC Controller different route name using the same cshtml as view.Net MVC 控制器不同的路由名称使用相同的 cshtml 作为视图
【发布时间】:2017-09-15 00:45:51
【问题描述】:

在 .NET MVC 中,我看到它始终遵循以下命名约定:控制器中的 RouteName,它是一个名为“RouteName.cshtml”的视图。

我的问题是如何使用具有不同 RouteName 的相同 cshtml 文件?

【问题讨论】:

标签: c# .net controller


【解决方案1】:

默认 View() 方法默认匹配 Action 名称,但您可以使用 View(string) 方法指定所需 CSHTML 的路径,如下例所示:

// in action method that is *not* RouteName
return View("RouteName");

【讨论】:

  • 谢谢。目前我`return View(myViewModel)`,你能告诉我在哪里可以找到API,以便我可以将路由名称和模型指定到我的视图吗?
  • 查看msdn.microsoft.com/en-us/library/… 的文档,您正在寻找的内容听起来像是采用 (string, object) 参数列表的重载,其中字符串参数是视图名称,对象参数是你的模型。
【解决方案2】:

您可以通过 partials 重复使用 CSHTML 块;根据您要解决的问题,这可能是更好的解决方案。

您可以编辑您的问题并添加更多上下文吗?为什么需要从多个 ActionResult 方法渲染相同的 cshtml?你想完成什么?

【讨论】:

    【解决方案3】:

    例如,您有一个名为 About.cshtml 的视图 您有 2 个操作方法,它们都使用 About.cshtml

    所以你可以试试

    public ActionResult Index()
            {
            var model = "view model";
            // Pass view model as the second parameter
            return View("About", model);
            }
    
    public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
                // Not need pass view name because view name and action method name are same (About
                return View();
            }
    

    【讨论】:

      猜你喜欢
      • 2014-10-07
      • 1970-01-01
      • 2010-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-04
      相关资源
      最近更新 更多