ViewContext.RouteData.Values ["action"]在服务器上为空...在本地计算机上正常工作

rks*_*rst 5 c# asp.net asp.net-mvc routing asp.net-mvc-routing

我有一个奇怪的问题,其中ViewContext.RouteData.Values ["action"]在我的登台服务器上为空,但在我的开发机器(asp.net开发服务器)上工作正常.

代码很简单:

public string CheckActiveClass(string actionName)
    {
        string text = "";
        if (ViewContext.RouteData.Values["action"].ToString() == actionName)
        {
            text = "selected";
        }
        return text;
    }
Run Code Online (Sandbox Code Playgroud)

我在ViewContext.RouteData.Values ["action"]行上收到错误.错误是:

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例.

任何帮助表示赞赏.提前致谢.

Jim*_*ert 2

您的开发服务器和登台服务器上是否有不同版本的 asp.net mvc?尝试将 System.Web.Mvc 本地复制到临时服务器,看看是否可以修复该问题。(右键单击引用,选择属性,然后将“复制本地”更改为“true”)

这可能对您的情况有帮助,也可能没有帮助,但这里有一个我从 asp.net/mvc 上的 MVC 模板偷来的辅助扩展:

/// <summary>
/// Checks the current action via RouteData
/// </summary>
/// <param name="helper">The HtmlHelper object to extend</param>
/// <param name="actionName">The Action</param>
/// <param name="controllerName">The Controller</param>
/// <returns>Boolean</returns>
public static bool IsCurrentAction(this HtmlHelper helper, string actionName, string controllerName)
{
    string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
    string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];

    if (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) && currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase))
        return true;

    return false;
}
Run Code Online (Sandbox Code Playgroud)