简体   繁体   中英

ViewContext.RouteData.Values[“action”] is null on server… works fine on local machine

I'm having a weird issue where ViewContext.RouteData.Values["action"] is null on my staging server, but works fine on my dev machine (asp.net development server).

The code is simple:

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

I get the error on the ViewContext.RouteData.Values["action"] line. The error is:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Any help is appreciated. Thanks in advance.

Do you have different versions of asp.net mvc on your dev and staging servers? Try copying System.Web.Mvc locally to the staging server and see if that fixes it. (Right click on the reference, choose properties, and change Copy Local to true)

This may or may not help your situation, but here is a helper extension I stole from an MVC template on asp.net/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;
}

I can't speak to why it works one place and not another, but:

  1. You should break the code up into several lines to figure out exactly what is null (var route = ViewContext.RouteData; var values = ...;), etc.

  2. Where are you calling CheckActiveClass from? At what time? Where's it located? ViewContext isn't always available everywhere. But you'll have a better idea of what's not available after #1.

James

Try using capitals

String currentController = ViewContext.RouteData.Values["Controller"].ToString(); String currentAction = ViewContext.RouteData.Values["Action"].ToString(); String currentID = ViewContext.RouteData.Values["ID"].ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM