Error
System.NullReferenceException: ‘Object reference not set to an instance of an object.’
System.Web.Mvc.WebViewPage.Model.get returned null.
I’m try to create a quiz app where user can give quiz exam and from admin side they can create a quiz. I used a .NET framework for it,
Thanks for your response
My view:
@model QuizApp.Models.tbl_questions
@{
Layout = null;
}
<!DOCTYPE html>
<body>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Quiz Start</h4>
@if (@ViewBag.Message != null)
{
<div class="alert alert-danger">
<strong>Error!</strong> @ViewBag.Message
</div>
}
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.q_text, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DisplayFor(model => model.q_text, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.q_text, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.QA, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<span> @Html.RadioButtonFor(model => model.QA, new { htmlAttributes = new { @class = "form-control" } }) @Model.QA </span>
@Html.ValidationMessageFor(model => model.QA, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.QB, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<span> @Html.RadioButtonFor(model => model.QB, new { htmlAttributes = new { @class = "form-control" } }) @Model.QB </span>
@Html.ValidationMessageFor(model => model.QB, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
Error appears on this line
}) @Model.QA
Controller:
public ActionResult StartQuiz()
{
tbl_questions q = null;
if (TempData["q_id"] != null)
{
int examId = Convert.ToInt32(TempData["examid"]);
q = db.tbl_questions.FirstOrDefault(x => x.q_fk_cat_id == examId);
//tbl_questions q = db.tbl_questions.Where(x => x.q_fk_cat_id == examId ).SingleOrDefault();
}
else
{
ViewBag.Message = "No Questions Found!";
}
return View(q);
}
When I login and try to enter in quiz its return null reference When there is a data in database.
I try to modify this line:
q = db.tbl_questions.First(x => x.q_fk_cat_id == examId);tbl_questions q = db.tbl_questions.Where(x => x.q_fk_cat_id == examId ).SingleOrDefault();
to this:
q = db.tbl_questions.FirstOrDefaul(x => x.q_fk_cat_id == examId);
but it does not work, I still get the same error. I don’t know why it takes null reference when there is a already 4 data in the database is available.
New contributor
1