When I click on the submit button in the example below, I get an error message like this one:
No parameterless constructor defined for this object.
After getting the error message I am unable to continue using the application. I tried to debug but I don't get any useful information to help in fixing the issue.
Controller:
[MvcApplication.SessionExpire]
[HttpGet]
public ActionResult Index()
{
DataLinqDB db = new DataLinqDB();
OpgaverPage model = new OpgaverPage();
var random = new Random();
var antalopgaver = db.opgavers.Count();
var number = random.Next(antalopgaver);
List<opgaver> List = db.opgavers.Skip(number).Take(1).ToList();
var A = db.opgavers.Skip(number).Take(1).FirstOrDefault();
model.Overskift = A.overskift;
model.OpgaveValueList = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = A.svar1, Value = "A"},
new SelectListItem { Selected = false, Text = A.svar2, Value = "B"},
new SelectListItem { Selected = false, Text = A.svar3, Value = "C"},
}, "Value", "Text", 1);
//angiver id til opgaven
model.HiddenId = A.Id;
//Fremvis hvornår man har fået point
//List<pointantal> PointValue = db.pointantals.Where(x => x.omrade == o && x.brugerid == brugerId).OrderByDescending(i => i.Id).Take(20).ToList();
//model.ListPoint = PointValue.ToList();
return View(model);
}
//error her
[MvcApplication.SessionExpire]
[HttpPost]
public ActionResult index(OpgaverPage opgavervalue)
{
if (ModelState.IsValid)
{
DataLinqDB db = new DataLinqDB();
var opgaver = db.opgavers.FirstOrDefault(i => i.Id == opgavervalue.HiddenId);
if (opgaver != null)
{
if (new SelectList(opgavervalue.OpgaveValueList).SelectedValue.ToString() == "A"
|| new SelectList(opgavervalue.OpgaveValueList).SelectedValue.ToString() == "B"
|| new SelectList(opgavervalue.OpgaveValueList).SelectedValue.ToString() == "C")
{
Value();
}
else
{
//error
ModelState.AddModelError("", "Desværre dit svar forkert");
}
}
else
{
return RedirectToAction("index", opgavervalue);
}
}
return View();
}
Model:
public class OpgaverPage
{
public string Overskift
{
get; set;
}
public int HiddenId
{
get; set;
}
[Display(Name ="Spørgsmål")]
public string Svar
{
get; set;
}
public SelectList OpgaveValueList
{
get; set;
}
public List<opgaver> ListPoint
{
get; set;
}
}
View:
@using (Html.BeginForm("index", "spil"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(i => i.HiddenId)
<div class="form-group">
@Html.LabelFor(x => x.Svar)<br />
@Html.DropDownListFor(x => x.OpgaveValueList, Model.OpgaveValueList, new
{
@class = "form-control"
})
</div>
<button type="submit" class="btn btn-effect-ripple btn-success"><i class="fa fa-check"></i> Tjek mit svar</button>
}
I tried to follow the answer here but I was unable to fix the issue: ASP.NET MVC Dropdown List From SelectList
What is causing this issue?