You have no view model . This is a hybrid class that you called the view model and in which you wrapped the domain object ( Question ). This is bad, do not do it.
Here I would recommend you. Start by developing a real presentation model that will reflect the requirements of your presentation (from your current description, this is a drop-down list containing some types of questions and allowing the user to select some type of question from this ddl):
public class QuestionViewModel { [DisplayName("Question_Type")] public string SelectedQuestionType { get; set; } public IEnumerable<SelectListItem> QuestionTypes { get; set; }
then map the controller card between your domain model and the view model. Of course, a further improvement will be to use AutoMapper to avoid this mapping across all actions of your controller:
public ActionResult Edit(int id) { var question = db.Question.Single(q => q.question_id == id); var qvm = new QuestionViewModel {
and then:
<div class="editor-label"> @Html.LabelFor(x => x.SelectedQuestionType) </div> <div class="editor-field"> @Html.DropDownListFor( x => SelectedQuestionType, new SelectList(Model.QuestionTypes, "Value", "Text") ) @Html.ValidationMessageFor(x => x.SelectedQuestionType) </div>
ViewBag/ViewData final note: make sure you get rid of any ViewBag/ViewData and put everything you need in your view model. You showed some categories in the action of your controller that were not implemented in the shown fragment of the view. If you ever needed them, just put them in your look model, just as we did with the types of questions.
source share