简体   繁体   English

空引用异常,在选项卡之间切换

[英]Null Reference Exception which switching between tabs

In my controller, I have something like this: 在我的控制器中,我有类似以下内容:

 [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public ActionResult Index()
    {

    int treatmentId = (int)UserSession.GetValue(StateNameEnum.ID, "TreatmentID");

    List<int> Ids = db.frames.Where(f => f.PlanId == treatmentId).Select(f => f.Id).ToList();
        int Id = Ids[0];

    PlanViewModel vm = new PlanViewModel();  

    case_info info = db.info.Where(r => r.Id == Id && r.LocationId ==     (int)LocationEnum.Proximal).Select(r => r).First();

    if (info.IsReference == 1)
    {
        vm.ReferenceId = ReferenceTypeEnum.Proximal.ToString();
    }
    else
    {
        vm.ReferenceId = ReferenceTypeEnum.Distal.ToString();
    }
    return PartialView(vm);

    }

and in my view I have this code: 在我看来,我有以下代码:

@if (Model.ReferenceId == "Proximal") //Getting Null Reference Exception here
{
    <span class="circle Plan-circle" style="background-color: rgb(255,0,0)"></span>
}
else if (Model.ReferenceId == "Distal")
{
    <span class="circle Plan-circle" style="background-color: rgb(0,0,255)"></span>
} 

In my view, that's the kind of logic I want to use to check if the ReferenceId is set to a specific string or not and change the view based on that value from the model. 在我看来,这是我想用来检查ReferenceId是否设置为特定字符串并根据模型中的值更改视图的逻辑。

However, I noticed while the above works sometimes, I noticed I get a null exception when switching between tabs. 但是,我注意到虽然上述方法有时可行,但我注意到在选项卡之间切换时会得到null异常。 I wonder why my model is null and if it makes sense how I'm grabbing the logic from the controller? 我想知道为什么我的模型为空,以及从控制器获取逻辑的方式是否有意义?

Using what I have set up in the controller, how can I check for when the model is set to a specific value in the view? 使用我在控制器中设置的内容,如何在视图中将模型设置为特定值时进行检查?

EDIT: 编辑:

Js file that's called when switching tabs: 切换标签时调用的js文件:

  ToggleTabSwitch: function (data) {

            var tabSelector = $('#tab-selector'); // any id you input in the first div
            tabSelector.on('click', '.newUI-left-selector', function () {
                $(this).removeClass('-newUI-left-selector');
                $(this).addClass('newUI-toggled-left-selector');

                //left selector toggled.
                $.ajax({
                    url: BrowserSide.Url.getFullUrl("DeformityPlanning/LoadDPPartialView"),
                    type: 'GET',
                    cache: false,
                    success: function (result) {
                        $('#selector-render').html(result);

                        BrowserSide.Plan.enableButtons();

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        BrowserSide.AjaxLog.HandleAjaxCallFail(XMLHttpRequest, textStatus, errorThrown, "ajax error in Plan.js Load DP_form view", "");
                    }
                });

                var rightToggedSelector = $('.newUI-toggled-right-selector');
                if (rightToggedSelector.length > 0) {
                    rightToggedSelector.removeClass('newUI-toggled-right-selector');
                    rightToggedSelector.addClass('newUI-right-selector');
                }
            });

            tabSelector.on('click', '.newUI-right-selector', function () {
                $(this).removeClass('newUI-right-selector');
                $(this).addClass('newUI-toggled-right-selector');

                // right selector toggled

                $.ajax({
                    url: BrowserSide.Url.getFullUrl("DeformityPlanning/LoadAPPartialView"),
                    type: 'GET',
                    cache: false,
                    success: function (result) {
                        $('#selector-render').html(result);
                        btnList = $("button[data-val-btnName]");
                        BrowserSide.Plan.enableButtons();

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        BrowserSide.AjaxLog.HandleAjaxCallFail(XMLHttpRequest, textStatus, errorThrown, "ajax error in Plan.js Load DP_formtwo view", "");
                    }
                });

                var rightToggedSelector = $('.newUI-toggled-left-selector');
                if (rightToggedSelector.length > 0) {
                    rightToggedSelector.removeClass('newUI-toggled-left-selector');
                    rightToggedSelector.addClass('newUI-left-selector');
                }
            });
        }

How I return the partial views in controller: 我如何在控制器中返回部分视图:

    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public ActionResult LoadDPPartialView()
    {
        return PartialView("DP_form");
    }

    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public ActionResult LoadAPPartialView()
    {
        List<PlanViewModel.PlanViewParam> newItem = new List<PlanViewModel.PlanViewParam>();

        return PartialView("DP_formtwo");
    }

EDIT #2: 编辑#2:

Attempt to fixing the problem: 尝试解决问题:

private void GetReferenceId()
    {

        int treatmentId = (int)UserSession.GetValue(StateNameEnum.ID, "TreatmentID");

        PlanViewModel vm = new PlanViewModel();

        List<int> Ids = db.frames.Where(f => f.PlanId == treatmentId).Select(f => f.Id).ToList();
        int Id = Ids[0];

         case_info info = db.info.Where(r => r.Id == Id && r.LocationId == (int)LocationEnum.Proximal).Select(r => r).First();

        if (info.IsReference == 1)
        {
            vm.ReferenceId = ReferenceTypeEnum.Proximal.ToString();
        }
        else
        {
            vm.ReferenceId = ReferenceTypeEnum.Distal.ToString();
        }
    }

    public ActionResult LoadDPPartialView()
    {
            GetReferenceId();
            return PartialView("DP_form");
    }

The logic you show for your Razor/CSHTML seems fine. 您为Razor / CSHTML显示的逻辑看起来不错。 It's very specialized to display/presentation since it's just choosing a color, so IMO it's appropriate in the view. 因为它只是选择一种颜色,所以它非常专门用于显示/演示,因此IMO在视图中很合适。 Nothing that I would call business logic. 我没有什么可以称为业务逻辑。

Although it could be made more DRY with a helper function of something like ReferenceTypeToRgbColor and use that in the style or even better emit a class and put your style in CSS. 尽管可以使用ReferenceTypeToRgbColor之类的辅助函数使它更干燥,然后在样式中使用它,甚至最好发出一个类并将样式放入CSS。 I'd also probably suggest using an enum or constants instead of string "Proximal", but that's another story. 我可能还会建议使用枚举或常量而不是字符串“ Proximal”,但这是另一回事了。

@function string CircleTypeToCssClass(string circleType)
{ 
    if (circleType == "Proximal")
    {
        return "proximal-circle";
    }
    else if (circleType == "Distal")
    {
         return "distal-circle";
    } 
    else 
       return "";
}

<span class="circle Plan-circle @(CircleTypeToCssClass(Model.ReferenceId))"></span>

Are sure that your exception comes from the Razor view and not from the controller? 确保您的异常来自Razor视图,而不是来自控制器?

case_info info = db.info.Where(r => r.Id == Id && r.LocationId ==     (int)LocationEnum.Proximal).Select(r => r).First();

.First() will throw an exception, if the resultset is empty. 如果结果集为空,则.First()将引发异常。 Try using .FirstOrDefault() instead 尝试改用.FirstOrDefault()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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