pass two models to view

56,999

Solution 1

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);
}

Solution 2

You have to create a new model which has to contain the whole objects that you want to pass it to view. You should create a model (class, object) which inherits the base model (class, object).

And other suggestion you may send objects (models) via View["model1"] and View["model2"] or just an array that contains objects to pass it and cast them inside the view which I don't advise .

Solution 3

It sounds like you could use a model that is specific to this view.

public class MyViewModel{

  public List<Currencies> CurrencyList {get;set;}

}

and then from your controller you could pass this new View Model into the view instead:

    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(new MyViewModel { CurrencyList = model.ToList() });
    }

You can than just add more properties to your view model which contain any other models (Weather model) and set them appropriately.

Share:
56,999
Arif YILMAZ
Author by

Arif YILMAZ

c#, mvc, web api, sql, t-sql, html5, jquery, css, angularjs

Updated on February 04, 2020

Comments

  • Arif YILMAZ
    Arif YILMAZ over 4 years

    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);
        }