【问题标题】:System.NullReferenceException in controller ASP.Net MVC控制器 ASP.Net MVC 中的 System.NullReferenceException
【发布时间】:2023-03-24 03:55:01
【问题描述】:

使用(简单的保龄球游戏网络应用),其中有两个文本框和一个提交按钮。

文本框 1 = FirstRoll ,文本框 2 = SecondRoll

用户输入两个数字并点击提交按钮,然后显示一个分数。

问题:在提交操作方法中获取System.NullReferenceException。为什么一开始框架是空的?

控制器

    [HttpPost]
    public JsonResult Submit(Frame[] _frames)
    {
        int result= 0;
        var objBowlingScore = new GameEngineService();

        foreach(var frame in _frames)
        {
            result = objBowlingScore.CalculateFrameScore(frame);
        }

        return Json(objBowlingScore);
    }

型号 为了代码的可读性,删除了服务器端检查验证

public class Frame
{
    public int FrameId { get; set; }
    public int FirstRoll { get; set; }
    public int SecondRoll { get; set; }
    public int ThirdRoll { get; set; }
    public int Score { get; set; }

}

查看

<p>1st Roll: @Html.EditorFor(m => m.FirstRoll)</p>
<p>2nd Roll: @Html.EditorFor(m => m.SecondRoll)</p>

<button id="submitButton" class="btn btn-primary btn-lg">Submit Score</button>

<p><label>The current frame is : </label><label id="lblFrameCount"></label></p>
<p><label>The current score is : </label><label id="lblTotalScore"></label></p>

@section DocumentReady {
<script type="text/javascript">

        var bowlingData = { "frames": [] };
        $('#submitButton').click(function (e) {
            var temp = {
                "firstroll": $("#FirstRoll").val(),
                "secondroll": $("#SecondRoll").val()
            };

            bowlingData.frames.push(temp);
            var element = this;

            $.ajax({
                url: "/Home/Submit",
                type: "POST",
                data: JSON.stringify(bowlingData),
                dataType: "json",
                traditional: true,
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $("#lblTotalScore").text(data.Score);
                    $("#FirstRoll").val("");
                    $("#SecondRoll").val("");
                },
                error: function () {
                    alert("An error has occured!!!");
                }
            });
        });

</script>

服务

    ....
    public int CalculateFrameScore(Frame _frame)
    {
        return _frame.FirstRoll + _frame.SecondRoll + _frame.ThirdRoll;
    }

    ....

【问题讨论】:

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


    【解决方案1】:

    问题是提交方法中的参数名称与jQuery 事件处理程序中使用的参数不匹配。

    _frames 应该是 frames。 (即

    曾经

    公共 JsonResult 提交(Frame[] _frames))

    应该是

    公共 JsonResult 提交(Frame[] 帧))

    【讨论】:

    • public JsonResult Submit(Frame[] frames))
    猜你喜欢
    • 2021-11-22
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    相关资源
    最近更新 更多