user952072
user952072

Reputation: 107

combine 2 related model in mvc

I have 2 models like this.

 public partial class Question
    {
        public int QuestionId { get; set; }        
        public string QuestionText { get; set; }
        public string Ans1 { get; set; }
        public string Ans2 { get; set; }
        public string Ans3 { get; set; }
        public string Ans4 { get; set; }
    } 
    public partial class UserAnswer
    {
        public int UserAnsId { get; set; }
        public Nullable<int> QuestionId { get; set; }
        public Nullable<int> UserId { get; set; }
        public Nullable<int> AnsVal { get; set; }        
    }

As you can see QuestionId is in both the models. How can I render it in view. There are multiple questions. Question Moldel has data in initial run but UserAnswer doesn't.

How can I combine these 2 models so that I can use it as IEnumerable in view. Ans1,Ans2,Ans3,Ans4 has text and AnsVal in UserAnswer will get its value from Raiobutton.

Upvotes: 0

Views: 445

Answers (2)

Neel
Neel

Reputation: 11731

make a combine class like below..i am not sure this is perfect or not..any suggestions are acceptable.

public class QuestionAnswerViewModel 
{ 
    public Question Question {get;set;}
    public ICollection<UserAnswer> Answers {get;set;}
}

Upvotes: 2

Brian Ogden
Brian Ogden

Reputation: 19212

You want to create a ViewModel that represents the combined model objects. This keeps things clean, your model is just that, the model, what gets passed to the view can be the model but in many cases the concept of a ViewModel will make things easier to design while keeping your code loosely coupled and clean. This also keeps things that are not important to the View out of the equation aka particular properties in your model such as maybe a CreatedDate should not be passed to the View, especially since View requests will pass back the value as null since it is not being used in the view and thus not populated on postback. This could lead to you updating the database with a null value for CreatedDate simply because it was not used in the View.

Maybe you have a Model class library in your solution? If you do, create another class library called MyNamespace.Web.ViewModels or something like that. Also you should look into using a tool like AutoMapper that will populate the ViewModel on View request to the Controller and populate the model on View postback to the controller.

Upvotes: 0

Related Questions