Quantcast
Channel: CodeProject Latest postings for ASP.NET
Viewing all articles
Browse latest Browse all 3938

Cannot get ViewModel in MVC5 to work

$
0
0
I am trying to incorporate a ViewModel as I am using edmx file to define my db, but my view only works with the edmx model and sends an unexpected result when I use my ViewModel.
 
My ViewModel is;
publicclass GetQuestionViewModel
   {
        publicclass Question { 
        public Question Questions { get; set; }
        public Response Response { get; set; }
        }
        public GetQuestionViewModel()
        {
            this.QuestionOptions = new HashSet<QuestionOption>();
            this.Responses = new HashSet<Response>();
        } 
        [Key]
        publicint Id { get; set; }
        publicint PageNumber { get; set; }
        publicstring Question1 { get; set; }
        publicint QuestionTypeId { get; set; }
        public Nullable<int> LinkedTo { get; set; }
        public Nullable<int> Options { get; set; }
        public Nullable<int> QuestionRanking { get; set; }
 
        publicvirtual ICollection<QuestionOption> QuestionOptions { get; set; }
        publicvirtual QuestionType QuestionType { get; set; }
        publicvirtual ICollection<Response> Responses { get; set; }
   }
 
And my Action is;
        [HttpGet]
        public ActionResult ViewQuestion(int? id)
        {
            if (id == null || id == 0 || id > 13)
            {
                id = 8;
            }
            Question question = db.Questions.Find(id);
 
            if (question == null)
            {
                return HttpNotFound();
            }
            return View(question);
        }
 
I tried changing the
Question question = db.Questions.Find(id);
to
var question = db.Questions.Find(id);
but nothing I have tried works. I want to get the ViewModel working before I build the query;
Question questions =  (from q in db.Questions
        from qo in q.QuestionOptions.DefaultIfEmpty()
        from r in q.Responses.DefaultIfEmpty()
        where q.PageNumber == page && r.UserId == userId
        select new Question 
        {
           Id = q.Id,
           QuestionType = q.QuestionType,
           Question1 = q.Question1
        }
 
This is my first MVC project and I am really struggling although I have followed several online tutorials. I would be grateful for any help.

Viewing all articles
Browse latest Browse all 3938

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>