Arrays 控制器ASP.Net MVC中的System.NullReferenceException
使用(简单保龄球游戏web应用程序),其中有两个文本框和一个提交按钮 文本框1=第一卷,文本框2=第二卷 用户输入两个数字,点击提交按钮,然后显示分数 问题:在提交操作方法中获取Arrays 控制器ASP.Net MVC中的System.NullReferenceException,arrays,json,asp.net-mvc,model-view-controller,razor,Arrays,Json,Asp.net Mvc,Model View Controller,Razor,使用(简单保龄球游戏web应用程序),其中有两个文本框和一个提交按钮 文本框1=第一卷,文本框2=第二卷 用户输入两个数字,点击提交按钮,然后显示分数 问题:在提交操作方法中获取系统.NullReferenceException。为什么一开始框架是空的 控制器 [HttpPost] public JsonResult Submit(Frame[] _frames) { int result= 0; var objBowlingScore =
系统.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>
问题是Submit方法中的参数名称与
jQuery
事件处理程序中使用的参数不匹配
\u frames应该是frames。(即
是
公共JsonResult提交(帧[]_帧))
应该是
公共JsonResult提交(帧[]帧))
publicjsonresult提交(Frame[]frames))
....
public int CalculateFrameScore(Frame _frame)
{
return _frame.FirstRoll + _frame.SecondRoll + _frame.ThirdRoll;
}
....