【发布时间】:2012-07-27 04:35:50
【问题描述】:
我有一个唯一的'字符串'不包含定义问题。
查看以下代码:
@if (ViewBag.Stories != null)
{
if (ViewBag.Stories.Count > 0)
{
<h2>Stories (@ViewBag.Stories.Count)</h2>
<ul>
@foreach (var item in ViewBag.Stories)
{
<li>
@("test".ToString().ToSeoUrl())
<h2>@(item.Title.ToString().ToSeoUrl())</h2>
</li>
}
</ul>
}
}
如果我从 item.Title 中删除 '.ToString().ToSeoUrl()' 我会得到:
-
测试
标题
-
测试
标题
-
测试
标题
如果我把它加回来。我得到了例外
“/”应用程序中的服务器错误。
“字符串”不包含“ToSeoUrl”的定义
我正在使用 Razor,并在视图中注册了以下帮助程序类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
namespace MyNamespace.Helpers
{
public static class StringExtensions
{
public static string ToSeoUrl(this string url)
{
// make the url lowercase
string encodedUrl = (url ?? "").ToLower();
// replace & with and
encodedUrl = Regex.Replace(encodedUrl, @"\&+", "and");
// remove characters
encodedUrl = encodedUrl.Replace("'", "");
// remove invalid characters
encodedUrl = Regex.Replace(encodedUrl, @"[^a-z0-9]", "-");
// remove duplicates
encodedUrl = Regex.Replace(encodedUrl, @"-+", "-");
// trim leading & trailing characters
encodedUrl = encodedUrl.Trim('-');
return encodedUrl;
}
}
}
item 是一个名为 Story 的自定义类,带有一个公共字符串 Title
【问题讨论】:
-
辅助类是如何在视图中“注册”的?
-
我还尝试将注册的命名空间移出到 web.config 并将调用放在 @{} 中,但没有成功。
-
@using MyNamespace.Helpers;并在 web.config(顶级和视图级别)
标签: c# asp.net-mvc razor