循环浏览ViewBag时,'string'不包含helper的定义

Kai*_*mer 1 c# asp.net-mvc razor

我有一个独特的'字符串'不包含定义问题.

请遵循以下VIew代码:

@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>
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我从item.Title中删除'.ToString().ToSeoUrl()',我得到:

  • 测试

    标题

  • 测试

    标题

  • 测试

    标题

如果我把它添加回去.我得到了例外

'/'应用程序中的服务器错误.

'string'不包含'ToSeoUrl'的定义

我正在使用Razor并在View中注册了以下帮助器类:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

item是一个名为Story的自定义类,带有公共字符串Title

nem*_*esv 5

无法动态分派扩展方法.由于您使用的ViewBagdynamicToSeoUrl这是一个扩展方法,你会得到一个RuntimeBinderException.

有两种方法可以解决这个问题:

  1. 使用强制转换:<h2>@(((string)item.Title).ToSeoUrl())</h2>调用ToString()是不够的,因为它也将被动态调度.
  2. 在没有扩展方法语法的情况下调用扩展方法作为常规静态方法: <h2>@(StringExtensions.ToSeoUrl(item.Title))</h2>