This is my Controller code.
public ActionResult Create(int? surveyGetter)
{
var survey = db.Surveys.FirstOrDefault(s => s.SurveyID == 1);
if (survey != null){
string question = survey.Question1;
ViewBag.Question1 = question;
}
else if (survey == null) { ViewBag.Question1 = "Failed to retrieve Question from database."; }
ViewBag.SurveyID = new SelectList(db.Surveys, "SurveyID", "SurveyName");
return View();
}
This example gets the database value of SurveyID == 1.
What I wish to do is let the input value surveyGetter replace the hardcoded 1, so that I can get the SurveyID value based on the surveyGetter value beening input.
Changing the 1 to surveyGetter gives null value.
Is this perhaps because of the FirstOrDefault expression? What expression must I change it to?
Answered by Daniel J.G.
How have you set your routes? If you are using the default {controller}/{action}/{id} then you have to rename surveyGetter as id.
Working code:
public ActionResult Create(int? id)
{
var survey = db.Surveys.FirstOrDefault(s => s.SurveyID == id);
if (survey != null){
string question = survey.Question1;
ViewBag.Question1 = question;
}
else if (survey == null) { ViewBag.Question1 = "Failed to retrieve Question from database."; }
ViewBag.SurveyID = new SelectList(db.Surveys, "SurveyID", "SurveyName");
return View();
}