Working with (simple bowling game web app) where there are two text boxes and one submit button.
text box 1 = FirstRoll ,text box 2 = SecondRoll
User enter two numbers and cilck submit button then displays a score.
Issue : Getting System.NullReferenceException in Submit action method. Why frame is empty in first instance?
Controller
[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);
}
Model server side check validations are removed for code readability
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; }
}
View
<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>
Service
....
public int CalculateFrameScore(Frame _frame)
{
return _frame.FirstRoll + _frame.SecondRoll + _frame.ThirdRoll;
}
....