gpt4 book ai didi

asp.net-mvc - HtmlHelper 中不能使用 ViewBag 中的值?

转载 作者:行者123 更新时间:2023-12-04 18:35:48 25 4
gpt4 key购买 nike

我有一个 HtmlHelper 来为我的页面标题和描述吐出 html。

public static class HeaderHelper
{
public static MvcHtmlString StandardHeader(this HtmlHelper htmlHelper,
string title,
string description="")
{
var tbSection= new TagBuilder("div");
tbSection.AddCssClass("page-header");

var tbTitle = new TagBuilder("h2") {InnerHtml = title};
if (!string.IsNullOrEmpty(description))
{
var tbDescription = new TagBuilder("p") {InnerHtml = description};
tbSection.InnerHtml = string.Concat(tbTitle, tbDescription);
}
else
{
tbSection.InnerHtml = tbTitle.ToString();
}

return MvcHtmlString.Create(tbSection.ToString());
}
}
它适用于
@Html.StandardHeader("View Employees")
@Html.StandardHeader("Edit Employee","...some description...")
但是当我使用 ViewBag 值时
@Html.StandardHeader(ViewBag.Title)
或者
@Html.StandardHeader(ViewBag.Title.ToString())
所以问题是:我们如何传入 ViewBag.Title变成一个 HtmlHelper?

更新
我的 @Html.StandardHeader(...)下面有红线陈述。
这是一个 编译错误

Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'StandardHeader' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.


我尝试了其他一些变体:
@{
var test = "test";
var title = string.Format("Welcome {0}", ViewBag.Title);
}
@Html.StandardHeader(test) // works
@Html.StandardHeader(title) // won't work :(
另外,我已经确定 ViewBag.Title不为空。

最终更新
只是对提供的解决方案再发表一些评论。
基本上,我们必须进行显式转换。
所有 C# 对象都有一个 .ToString()方法。但并非每个人都可以转换为字符串。一个 ViewBag value 本质上是一个对象,一个 .ToString()不是类型转换。
至于为什么一定要用 string而不是 var显式声明变量,
string title = string.Format("欢迎{0}", ViewBag.Title);
我在单独的 SO question 中得到了很好的答案.
从那里直接报价。

All expressions are evaluated at runtime, with the occasional exception of some operations on compile time literals.

So: if at least one of the parameters is dynamic, the entire expression is treated as it was dynamic and evaluated on runtime.


希望此更新有所帮助。

最佳答案

您需要投 ViewBag属性(因为 ViewBagdynamic )。

@Html.StandardHeader((string)ViewBag.Title)

在第二个例子中
@Html.StandardHeader((string)title)

或显式声明变量为 string而是 var
@{ string title = string.Format("Welcome {0}", ViewBag.Title); }
@Html.StandardHeader(title)

关于asp.net-mvc - HtmlHelper 中不能使用 ViewBag 中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350060/

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