将两个模型传递给视图

17

我是mvc的新手,正试着通过做一个小项目来学习它。我有一个页面,应该显示特定日期的货币和天气。所以我需要传递货币模型和天气模型。我已经成功传递了货币模型,但我不知道如何传递第二个模型。大多数教程只展示如何传递一个模型,请问你们能给一个想法吗?

这是我的当前控制器动作,它发送货币模型:

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

只需创建一个聚合模型类,其中包含您需要作为属性传递的2个模型即可。 - Sergey Akopov
3个回答

44

您可以创建一个特殊的 ViewModel,其中包含两个模型:

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

并将其传递给视图。

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

成功传递模型后,我如何从视图中访问不同的模型? - Mwas
1
使用 model.Currencies 获取 Currencies 的属性,使用 model.CurrentWeather 获取 CurrentWeather 的属性。 - Kirill Bestemyanov
@model在HTML中的当前上下文中不存在。 - Dimitris Kougioumtzis

6

您需要创建一个新模型,其中包含您想要传递给视图的所有对象。您应该创建一个继承基本模型(类、对象)的模型(类、对象)。

另外一个建议是通过View["model1"]和View["model2"]发送对象(模型),或者只是一个包含要传递的对象的数组,并在视图内进行转换,但我不建议这样做。


如何使用View发送它们?如何从控制器传递到视图? - Arif YILMAZ
在控制器类中,ViewData["CurrentTime"] = DateTime.Now.ToString();,在视图页面中为<div><%: ViewData["CurrentTime"] %></div>。如需更多详细信息,请参阅此链接link - nesimtunc

3

听起来你可能需要一个特定于此视图的模型。

public class MyViewModel{

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

}

然后,您可以从控制器将此新视图模型传递到视图中:

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

您可以向您的视图模型添加更多属性,包含任何其他模型(如天气模型),并适当设置它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接