【发布时间】: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