Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass two models to view [duplicate]

I am new to mvc and try to learn it by doing a small project with it. I have a page which is supposed to display that specific date's currencies and weather. so I should pass currencies model and weather model. I have done to pass currencies model and works fine but I dont know how to pass the second model. And most of the tutorials on the shows how to pass only one model.

can you guys give an idea how to do it.

this is my current controller action which sends currency model

public ActionResult Index(int year,int month,int day)
    {
        var model = from r in _db.Currencies
                    where r.date == new DateTime(year,month,day)
                    select r;

        return View(model);
    }
like image 278
Arif YILMAZ Avatar asked Jun 10 '13 18:06

Arif YILMAZ


People also ask

Can you pass two models one view?

Introduction. In MVC we cannot pass multiple models from a controller to the single view.

Can a view have multiple models?

Yes, you can use Tuple (brings magic in view having multiple model).


1 Answers

You can create special viewmodel that contains both models:

public class CurrencyAndWeatherViewModel
{
   public IEnumerable<Currency> Currencies{get;set;}
   public Weather CurrentWeather {get;set;}
}

and pass it to view.

public ActionResult Index(int year,int month,int day)
{
    var currencies = from r in _db.Currencies
                where r.date == new DateTime(year,month,day)
                select r;
    var weather = ...

    var model = new CurrencyAndWeatherViewModel {Currencies = currencies.ToArray(), CurrentWeather = weather};

    return View(model);
}
like image 153
Kirill Bestemyanov Avatar answered Sep 21 '22 20:09

Kirill Bestemyanov