@foreach上的MVC NullReferenceException(模型中的var项)

Baggerz

阅读完此内容后,出现以下错误

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

我了解错误是什么,但不了解错误的原因或在我的情况下如何解决,

谁能解释为什么?

错误:

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

在线错误:

@foreach(模型中的var项)

控制器:

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();
    }
  }
}

看法:

@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>

脱氧氧

如果我正确理解所有内容,则NullReferenceException在将POST请求发送到CheckUser控制器操作会收到一个此操作不会创建模型,并且会在此处返回没有模型的视图:

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

或在这里:

        return View("LogIn");

您可以检查Model您的视图中是否不为null(如其他答案中所述),但这将导致避免引发异常,用户仍将看到一个空表。要显示一些数据,您不需要直接从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");
    }
 }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

@foreach(模型中的变量项)是 NullReferenceException

MVC模型内的foreach循环

我如何在 mvc 中获取当前模型项

错误:MVC中“传递给字典的模型项为空”

在模型上使用JTable的MVC

如何退出循环遍历剃刀页面中 <td> 中的模型项的 foreach?

在MVC中的JavaScript中嵌套foreach

错误的模型项在 Asp.net mvc 中传递到字典中

jQuery更新Spring MVC中的<c:forEach>

在 foreach .net 4.5 mvc 中实现异步

传入字典的模型项在 Razor mvc5 中属于“System.Collections.Generic.List”类型

将模型收集中的一项发布到MVC中的控制器方法

Javascript函数不断从MVC模型列表中的最后一项检索数据

如何在Asp.NET MVC中修复“此词典需要类型的模型项”?

ASP.NET MVC 5传递到字典中的模型项的类型为“ Name.Models.IndexViewModel”,但此字典需要类型为的模型项

MVC在视图模型上按属性排序

模型之外的ASPNet MVC上的业务逻辑

Knockoutjs 上 foreach 中的单选按钮名称

foreach中的无限循环在simplexmlelement上

NullReferenceException显示MVC 5中的ValidateAntiForgeryToken

如何在swiftUI中的Foreach循环上显示除一项以外的图像?

如何将Mvc4模型项添加到mvc4中的jquery数组?

为什么MVC在GET上提供的模型上使用Modelstate

MVC中的模型管理

Spring MVC中的模型

Android上Environment.GetCommandLineArgs()中的NullReferenceException

System.Web.Mvc.FilterProviderCollection.GetFilters上的NullReferenceException

我正在使用Ajax发布到Mvc中的控制器,但是我的var在foreach中重置为null

在 Perl 中 foreach 我的 $var ($var, $var) 表达式