1

I have a view which contains data from 4 tables from the database. Do i need to define all of those fields in my model? so that i can use them in my view like :-

@model.fieldFromTable1
@model.fieldFromTable2
@model.fieldFromTable3
@model.fieldFromTable4
tereško
  • 58,060
  • 25
  • 98
  • 150
Ujjwal Vaish
  • 373
  • 1
  • 7
  • 21
  • possible duplicate of [MVC - Passing multiple data tables to a view](http://stackoverflow.com/questions/5488363/mvc-passing-multiple-data-tables-to-a-view) – stripthesoul May 21 '14 at 12:54
  • This looks similar , but I do not have anything linking the 2 tables , both contain individual data , say one of batsmen and other of bowlers , so I have to add each of the batting and bowling fields to my model , right? – Ujjwal Vaish May 21 '14 at 13:04
  • 1
    FYI: When asking a question, after typing in your question's title, below the field, a list of potential similar questions will appear. Always check this, first, before actually posting your question. I personally saw a handful of already asked and answered questions that would have fit the bill. – Chris Pratt May 21 '14 at 13:05
  • 1
    The answer to the linked question suggests using a view model. There's no condition that the data you put in that view model be linked in some way. – Chris Pratt May 21 '14 at 13:07

1 Answers1

2

The quick answer is yes. You can probably think of your model more as a ViewModel. Not an actual model from your database.

In your controller you would just populate the ViewModel from your database models

MyViewModel.cs

//put whatever properties your view will need in here 
public class MyViewModel 
{
    public string PropertyFromModel1 {get; set;}
    public string PropertyFromModel2 {get; set;}
}

MyController.cs

public ActionResult MyAction()
{ 
    //the only job your action should have is to populate your view model
    //with data from wherever it needs to get it
    Model1 model = GetFirstModelFromDatabase();
    Model2 model2 = GetSecondModelFromDatabase();

    MyViewModel vm = new MyViewModel 
    {
        PropertyFromModel1 = model.MyProperty;
        PropertyFromModel2 = model2.MyProperty;
    }

    return View(vm);
}

MyAction.cshtml

@Model.PropertyFromModel1
@Model.PropertyFromModel2

It's actually pretty standard practice to not use your raw domain models in your views, because I would say that typically don't match up exactly to what you want to display.

Kyle Gobel
  • 5,530
  • 9
  • 45
  • 68