无法在非静态上下文中访问静态方法

时间:2015-07-30 13:24:22

标签: c# asp.net asp.net-mvc static-methods

我创建了一个使用名为GetUrl的方法的局部视图,但我收到错误cannot access static method in a non static context

以下是我实施该方法的方法:

public class TimeLineStep
{
    public string Code { get; set; }
    public string Title { get; set; }
    public TimeLineStatus Status { get; set; }
    public string Description { get; set; }
    public string Category { get; set; }

    public static string GetUrl(string code)
    {
        switch (code)
        {
            case "1":
                return "#";
            case "2":
                return "#";
            case "3":
                return "#";
            case "4":
                return "#";
            case "5":
                return "#";
            case "6":
                return "#";
            case "7":
                return "#";
            default:
                return "#";
        }
    }
}

和我的部分观点:

@using UI.Controls
@model List<Web.Models.TimeLineStep>
@{
    Layout = null;
}
@using (Html.ContentBlock("Yellow", ""))
{
    <ul>
        @foreach (var menuItem in Model)
        {
            <li>
                <a href="@menuItem.GetUrl(menuItem.Code)"> @menuItem.Title </a>
            </li>
        }
    </ul>
}

此部分视图会生成包含网址的垂直菜单。如何调用静态方法?

1 个答案:

答案 0 :(得分:4)

您在类本身上调用静态方法,而不是类的实例。

<a href="@TimeLineStep.GetUrl(menuItem.Code)"> @menuItem.Title </a>

但你确定你打算让那个静止吗?看起来你想要的是:

public string GetUrl()
{
    switch (this.Code)
         ....

然后将被称为

<a href="@menuItem.GetUrl()"> @menuItem.Title </a>