gpt4 book ai didi

asp.net-mvc - 如何根据 Asp.Net MVC 中的 View 设置 类?

转载 作者:行者123 更新时间:2023-12-04 06:48:53 28 4
gpt4 key购买 nike

我想设置 <body>类以及基于 View 。

我已经阅读了一些关于强输入母版页的帖子,但似乎没有一个完全适合,或者至少我不知道如何编码。

我注意到 Stack Overflwow 做到了,所以它一定是可能的。

更新:

获取错误:Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.Compiler Error Message: CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'Body' and no extension method 'Body' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)body线

namespace MySite.Helpers
{
public static class HtmlHelpers
{
public static MvcHtmlString Body(this HtmlHelper htmlHelper)
{
string currentControllerName = (string)htmlHelper.ViewContext.RouteData.Values["controller"];
string currentActionName = (string)htmlHelper.ViewContext.RouteData.Values["action"];
string css = currentControllerName + "-" + currentActionName;
var body = new TagBuilder("body");
body.AddCssClass(css);
return MvcHtmlString.Create(body.ToString(TagRenderMode.StartTag));
}
}

}

~/Views/Shared/Site.Master:
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>

<body id="argh" class="<%= Html.Body() %>">

最佳答案

您可以使用辅助方法:

public static MvcHtmlString Body(this HtmlHelper htmlHelper)
{
string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
string css = GetCss(currentControllerName, currentActionName);
var body = new TagBuilder("body");
body.AddCssClass(css);
return MvcHtmlString.Create(body.ToString(TagRenderMode.StartTag));
}

然后在您的母版页中:
<%= Html.Body() %>
...
</body>

关于asp.net-mvc - 如何根据 Asp.Net MVC 中的 View 设置 <body> 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3406579/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com