asp.net-mvc @foreach 上的 MVC NullReferenceException(模型中的 var 项)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25742953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:13:47  来源:igfitidea点击:

MVC NullReferenceException on @foreach (var item in Model)

asp.net-mvcviewmodelnullreferenceexception

提问by Baggerz

I'm getting the below error, after reading through this

阅读完本文后,我收到以下错误

What is a NullReferenceException, and how do I fix it?

什么是 NullReferenceException,我该如何解决?

I understand what the error is but not how its being caused or how to fix it in my case,

我了解错误是什么,但不知道它是如何引起的或如何在我的情况下修复它,

Can anyone explain why?

谁能解释为什么?

Error:

错误:

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

System.NullReferenceException:未将对象引用设置为对象的实例。

Error on line:

在线错误:

@foreach (var item in Model)

@foreach(模型中的变量项目)

Controller:

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TMTMonitorandCompare.Models;


namespace TMTMonitorandCompare.Controllers
{

public class HomeController : Controller

{
 private MetaClone_2Entities db = new MetaClone_2Entities();
 public ActionResult Index(string filtername)        
    {

        var filterresults = from m in db.UserInfoes
                            select m;            

        filterresults = filterresults.Where(x => x.UserCode.ToString().Contains(filtername)).OrderBy(x => x.UserCode);

        return View(filterresults);
    }
    public ActionResult Login()
    {
        return View("Login");
    }
    public ActionResult CheckUser()
    {
        //check username & password
        if ((Request.Form["username"] == "user") && (Request.Form["password"] == "pass"))
        {
            // use forms auth class to set the cookie
            FormsAuthentication.SetAuthCookie(Request.Form["username"], true);
            // redirect to view
            return View("Index");
        }
        else
        {
            return View("Login");
        }
    }

    public ActionResult SessionTimeout()
    {
        return View();
    }
    public ActionResult ForgotPassword()
    {
        return View();
    }
  }
}

View:

看法:

@model IEnumerable<TMTMonitorandCompare.Models.UserInfo>
@{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
$(document).ready(function () {
    @*Validation for Text fields with name formpart*@
    $('#SendRequest').click(function (e) {
        var isValid = true;
        $("input[type='text'][name='formpart']").each(function () {
            if ($.trim($(this).val()) == '') {
                isValid = false;
                $(this).css({
                    "border": "1px solid red",
                    "background": "#FFCECE"
                });
            }
            else {
                $(this).css({
                    "border": "",
                    "background": ""
                });
            }
        });
        if (isValid == false)
            e.preventDefault();
        else
            alert('Thank you for submitting');
    });


    $("#resultsgo").click(function () {
        $("#basicModal2").modal('hide');
    });
    $("#bckpage").click(function () {
        $("#basicModal3").modal('hide');
        $("#basicModal2").modal('show');
    });
    $("#bcktostart").click(function () {
        $("#basicModal3").modal('hide');
    });

    $("#SendRequest").click(function () {
        var imei = ("IMEI: " + $("#imei").val());
        $('#printImei').html(imei);
        var phonenumber = ("Phone Number: " + $("#phoneNumber").val());
        $('#printPhoneNumber').html(phonenumber);
        var policynumber = ("Policy Number: " + $("#policyNumber").val());
        $('#printPolicyNumber').html(policynumber);
    });

    @*Code for passing code (Should work)*@
    $("#SendCodeRequest").click(function () {
        var thecode = ("Code: " + $("#theCode").val());
        $('#printCode').html(thecode);
    });


    @*Code for dropdowns ( not working)*@
    $('#pickButton').dropdown();
    $('#selectionDropdown li').on('click', function () {
        $('#dropdown_title').html($(this).find('a').html());
    });

});
</script>


<button type="button" class="btn btn-success pull-right" id="logonbutton" onclick="location.href = '@Url.Action("Logon", "Home")'">Logon</button>
<table class="table">
<thead>
    <tr>
        <th>New Request</th>
        <th>Existing Request</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>
            <form class="form-horizontal">
                <div class="form-group">
                    <label class="control-label col-xs-2" for="imei">IMEI:</label>
                    <div class="col-xs-9">
                        <input type="text" class="form-control" id="imei" name="formpart" placeholder="IMEI">
                    </div>
                </div>

                <div class="form-group">
                    <label class="control-label col-xs-2" for="phoneNumber">Phone Number:</label>
                    <div class="col-xs-9">
                        <input type="tel" class="form-control" id="phoneNumber" placeholder="Phone Number">
                    </div>
                </div>

                <div class="form-group">
                    <label for="platform" class="control-label col-xs-2">Policy Organisation:</label>
                    <div class="col-xs-10">
                        <div class="dropdown">
                            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
                                Select
                                <span class="caret"></span>
                            </button>
                            <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu2">
                                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">TMT Internals</a></li>
                            </ul>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="policyNumber" class="control-label col-xs-2">Policy Number:</label>
                    <div class="col-xs-10">
                        <input type="text" class="form-control" id="policyNumber" name="formpart" placeholder="Policy Number">
                    </div>
                </div>

                <div class="form-group">
                    <label for="platform" class="control-label col-xs-2">Platform:</label>
                    <div class="col-xs-10">
                        <div class="dropdown">
                            <button class="btn btn-default" id="pickButton" data-toggle="dropdown">
                                <span id="dropdown_title">Select</span>
                                <span class="caret"></span>
                            </button>
                            <ul class="dropdown-menu" id="selectionDropdown">
                                <li><a tabindex="-1" href="#">Android</a></li>
                                <li><a tabindex="-1" href="#">IOS</a></li>
                                <li><a tabindex="-1" href="#">Windows Phone</a></li>
                            </ul>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="diagnosticMode" class="control-label col-xs-2">Diagnostic Mode:</label>
                    <div class="col-xs-10">
                        <div class="dropdown">
                            <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown">
                                Select
                                <span class="caret"></span>
                            </button>
                            <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu3">
                                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Simple</a></li>
                                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Advanced</a></li>
                                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Mannual</a></li>
                                <li role="presentation"><a role="menuitem" tabindex="-1" href="#">Complete</a></li>
                            </ul>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-xs-offset-2 col-xs-10">
                        <a id="SendRequest" href="#" class="btn btn-success"
                           data-toggle="modal"
                           data-target="#basicModal">Create New Request</a>
                        <button type="submit" class="btn btn-primary">Back to List</button>
                    </div>
                </div>
            </form>
        </td>

        <td>
            <div class="form-group">
                <div class="col-xs-offset-2 col-xs-10">
                    <div class="span7 text-center">
                        <input type="text" class="form-control" id="theCode" placeholder="Please Enter Code">
                        <input type="submit" value="Go!" class="btn btn-success" id="sendcoderequest" data-toggle="modal"
                               data-target="#basicModal2" />
                    </div>
                </div>
            </div>

            @using (Html.BeginForm("Index", "Home", FormMethod.Get))
            {
                <p>
                    <label for="platform" class="control-label">Enter Code:</label><br />
                    @Html.TextBox("filtername")
                    <input type="submit" value="Filter" />
                </p>
            }

            <div class="modal fade" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">

                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&amp;times;</button>
                            <h4 class="modal-title" id="myModalLabel">Summary</h4>
                        </div>

                        <div class="modal-body">
                            <span id="printImei"></span><br />
                            <span id="printPhoneNumber"></span><br />
                            <span id="printPolicyNumber"></span>

                        </div>

                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Save changes</button>
                        </div>

                    </div>
                </div>
            </div>


            <div class="modal fade" id="basicModal2" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&amp;times;</button>
                            <h4 class="modal-title" id="myModalLabel">Summary</h4>
                        </div>
                        <div class="modal-body">
                            <h2>Results</h2>

                            <span id="printCode"></span><br />

                            <div class="pull-right"><button type="submit" class="btn btn-success" id="toggle">Toggle</button> </div>

                            <table class="table">
                                <thead>
                                    <tr>
                                        <th></th>
                                        <th>Date</th>
                                        <th>Test Type</th>
                                    </tr>
                                </thead>
                                <tbody>


                                    @foreach (var item in Model)
                                    {

                                        <tr>
                                            <td>
                                                <input type="checkbox">
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.CreationDateTime)
                                            </td>
                                            <td>
                                                @Html.DisplayFor(modelItem => item.AppModeId)
                                            </td>
                                        </tr>
                                    }

                                </tbody>
                            </table>
                            <div class="form-group">
                                <div class="col-xs-offset-2 col-xs-10">
                                    <a href="#" class="btn btn-success"
                                       data-toggle="modal"
                                       data-target="#basicModal3" id="resultsgo">Go!</a>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-success">Save changes</button>
                            <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>

                        </div>
                    </div>
                </div>
            </div>


            <div class="modal fade modal-lg" id="basicModal3" tabindex="-1" role="dialog" aria-labelledby="basicModal3" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">

                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&amp;times;</button>
                            <h4 class="modal-title" id="myModalLabel">Summary</h4>
                        </div>

                        <div class="modal-body">
                            <h2 id="tableheading">Comparison</h2>
                            <div class="btn-toolbar">
                                <div class="btn-group pull-left">
                                    <button type="button" class="btn btn-success" id="bcktostart">Back to Start</button>
                                    <button type="button" class="btn btn-success" id="bckpage">Back a Page</button>
                                </div>
                                <div class="btn-group pull-right">
                                    <button type="button" class="btn btn-success" id="singlebutton">Single</button>
                                    <button type="button" class="btn btn-success" id="multibutton">Multi</button>
                                </div>
                            </div>
                            <script>
                                $(document).ready(function () {
                                    $("#Table1").hide()
                                    $("#Table2").hide()
                                });
                                $("#multibutton").click(function () {
                                    $("#Table2").hide()
                                    $("#Table1").show()
                                    $("#tableheading").text('Multi-Comparision');
                                });
                                $("#singlebutton").click(function () {
                                    $("#Table1").hide()
                                    $("#Table2").show()
                                    $("#tableheading").text('Single-Comparision');
                                });
                            </script>

                            <table class="table table-striped" id="Table1">
                                <thead>
                                    <tr>
                                        <th>Phone 1</th>
                                        <th>Phone 2</th>
                                        <th>Phone 3</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>***Result***</td>
                                        <td>***Result***</td>
                                        <td>***Result***</td>
                                    </tr>
                                </tbody>
                            </table>
                            <table class="table table-striped" id="Table2">
                                <thead>
                                    <tr>
                                        <th>Phone 1</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>***Result***</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-success">Save changes</button>
                            <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </td>
    </tr>
</tbody>

回答by codebased

If ( Model != null ) {

@foreach (var item in Model)
                                    {

}
}

回答by takemyoxygen

If I understand everything correctly, you get a NullReferenceExceptionwhen a POST request is sent to CheckUsercontroller action. This action doesn't create a model and returns a view without a model here:

如果我理解一切正确,NullReferenceException当 POST 请求被发送到CheckUser控制器动作时,你会得到一个。此操作不会创建模型并在此处返回没有模型的视图:

        // redirect to view
        return View("Index");

or here:

或在这里:

        return View("LogIn");

You can check if your Modelis not null in your view as mentioned in other answers, but this will result in just avoiding an exception to be thrown, users will still see an empty table. To show some data you need not to return views directly from CheckUsermethod but redirect them to GET actions:

您可以检查Model您的视图中是否为空,如其他答案中所述,但这只会避免引发异常,用户仍然会看到一个空表。要显示一些数据,您不需要直接从CheckUser方法返回视图,而是将它们重定向到 GET 操作:

 public ActionResult CheckUser()
 {
     //check username & password
    if ((Request.Form["username"] == "user") && (Request.Form["password"] == "pass"))
    {
        // use forms auth class to set the cookie
        FormsAuthentication.SetAuthCookie(Request.Form["username"], true);
        // redirect to view
        return RedirectToAction("Index");
    }
    else
    {
        return RedirectToAction("Login");
    }
 }

回答by DaniCE

I think some or your filterresults items has UserCode property = null and that produces the exception. Replace your filter with

我认为某些或您的过滤器结果项具有 UserCode 属性 = null 并且会产生异常。更换您的过滤器

filterresults = filterresults.Where(x => x.UserCode != null 
      && x.UserCode.ToString().Contains(filtername)).OrderBy(x => x.UserCode);

回答by venkadesh m

@if(Model != null) 
{
    foreach (var item in Model)
    {
        // do your code
    }
}

回答by DrSnach

I'm pretty new in this, but I have just resolved this ABSOLUTE NIGHTMARE by changing the controller. I did this, and it work. It's a miracle

我在这方面很新,但我刚刚通过更改控制器解决了这个绝对的噩梦。我这样做了,并且有效。这是一个奇迹

public async Task<IActionResult> Administration()
{
    return View(await _context.Cause.ToListAsync());
}