Html Helpers 可以在 Razor 页面之外使用吗
我有一个类“IncomeStatement”,用作 ViewModel。这个类有一个属性,可以生成一些相当复杂的 html,如下所示:
public MvcHtmlString HtmlPeriods { get; set; }
....
StringBuilder htmlPeriods = new StringBuilder(100);
htmlPeriods.AppendFormat(
"<td><a href='/Forecast/IndexPeriod?Period={1}'>{0}</a></td>",
inc.NetSales, per.Period.PeriodID);
....
HtmlPeriods = MvcHtmlString.Create(htmlPeriods.ToString())
然后在 Razor 文件中,我使用 HtmlPeriods 属性,效果很好:
<th></th>@Model.HtmlPeriods<td></td>
但是,如果我想在我的类中使用 Html.ActionLink(...) 来创建,该怎么办?
很好的 Razorlike 链接, 像这样的事情:
string forecastLink =
Html.ActionLink("Edit Forecast", "/Forecast/IndexEdit?PeriodID=2005Q1");
我该怎么做?
I have a class 'IncomeStatement' that is used as a ViewModel. This class has a property that generates some fairly complicated html like this:
public MvcHtmlString HtmlPeriods { get; set; }
....
StringBuilder htmlPeriods = new StringBuilder(100);
htmlPeriods.AppendFormat(
"<td><a href='/Forecast/IndexPeriod?Period={1}'>{0}</a></td>",
inc.NetSales, per.Period.PeriodID);
....
HtmlPeriods = MvcHtmlString.Create(htmlPeriods.ToString())
Then in the Razor file I use the HtmlPeriods property, which works fine:
<th></th>@Model.HtmlPeriods<td></td>
But what if I want to use the Html.ActionLink(...) in my class to create
nice Razorlike links,
something like this:
string forecastLink =
Html.ActionLink("Edit Forecast", "/Forecast/IndexEdit?PeriodID=2005Q1");
How would I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 HtmlHelper 类来执行此操作。我想您会需要 GenerateLink 方法。
例子:
You can use the HtmlHelper class to do this. I think you will want the GenerateLink method.
Example:
在您的情况下,定义 HTML 帮助程序而不是在模型上使用属性和方法会更正确。例如:
然后在你看来:
In your situation it would be more correct to define HTML helpers instead of using properties and methods on your models. For example:
and then in your view: