首页 > 解决方案 > Check ViewContext.RouteData.Values to see if parameter exists

问题描述

How can I check to see if Values contains a parameter before assigning it to a variable?

null checks do not seem to work

    var offeringId;
    if (@ViewContext.RouteData.Values["offeringId"] == null) {
        offeringId = null;
    } else {
        offeringId = @ViewContext.RouteData.Values["offeringId"];
    }

    //the above line translates to the code below in the console when executed. 
    //If the value doesn't exist, nothing is displayed on the left side of the = operator.

    var offeringId;
    if ( == null) {
        offeringId = null;
    } else {
        offeringId = ;
    }

标签: javascriptasp.net-mvcmodel-view-controllerrazor

解决方案


首先这样做:

@{ string offeringValue = ViewContext.RouteData.Values["offeringId"] ?? "null";}

然后像这样分配offeringId

var offeringId = @offeringValue;

如果ViewContext.RouteData.Values["offeringId"] == null,您的脚本将如下所示:

var offeringId = null;

??null合并运算符(它将返回第一个不是 的值null


推荐阅读