【问题标题】:Check ViewContext.RouteData.Values to see if parameter exists检查 ViewContext.RouteData.Values 以查看参数是否存在
【发布时间】:2020-01-09 02:56:18
【问题描述】:

如何在将 Values 分配给变量之前检查其是否包含参数?

null 检查似乎不起作用

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

【问题讨论】:

  • 你应该移动var tempvalue = @ViewContext.RouteData.Values["offeringId"]
  • 删除ViewContext.RouteData.Values["offeringId"]之前的@。另外,如果值是 null 那为什么还要把它赋给 null 呢?

标签: javascript asp.net-mvc model-view-controller razor


【解决方案1】:

先这样做:

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

然后像这样分配offeringId

var offeringId = @offeringValue;

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

var offeringId = null;

??null 合并运算符(它将返回 firstnot null

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 2021-08-22
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多