I want to get a single database value into my Controller, set it to a ViewBag, and use that ViewBag in my View.
I have trired for hours but there is no examples to be found. My code looks like this:
Controller:
public class IntroResponsesController : Controller
{
...
ViewBag.Question1 = new SelectList(db.Surveys, "SurveyID", "Question1");
//I HAVE ALSO TRIED SOMETHING LIKE THIS:
if (db.Surveys.Find("Question1") != null)
{
ViewBag.Question1 = db.Surveys.Find("Question1");
}
}
View:
<h4>@ViewBag.Question1</h4>
My problem is that I do not have code that is meant to get a single value from database. What I have in the first example is a SelectList that is trying to get a list for filling a dropdownlist. That is not what I want to do!
Is there a substitute for the "new SelectedList" action that can give me what I want?
Notice also that the Controller is IntroResponseController and the Question1 is a property from the Survey Model.
Answered by Stephen Muecke:
Try
var survey = db.Surveys.FirstOrDefault(s => s.SurveyID == 1)
then
if survey is not null
string question = survey.Question1