Проверьте ViewContext.RouteData.Values, чтобы увидеть, существует ли параметр - PullRequest
0 голосов
/ 09 января 2020

Как я могу проверить, содержит ли Values ​​параметр, прежде чем присвоить его переменной?

Нулевые проверки не работают

    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 = ;
    }

1 Ответ

0 голосов
/ 09 января 2020

Сделайте это сначала:

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

Затем присвойте offeringId так:

var offeringId = @offeringValue;

Если ViewContext.RouteData.Values["offeringId"] == null, ваш скрипт будет выглядеть так:

var offeringId = null;

?? - это оператор объединения null (он вернет первое значение, которое не null)

...