如何访问在剃刀视图的数据? [英] How do I access data in a view in Razor?
问题描述
在标准的WebForms,我早就性能屈指可数,并且设置这些。然后,网页会绑定到他们,例如使用<%#客户名称%方式>
In standard WebForms, I would have a handful of properties, and set those. Then the Web Page would bind to them, for example with <%#CustomerName%>
.
据我所知,MVC是一种不同的方法,但仍有一定是在同一时间显示来自多个源的数据的基本需要。
I understand that MVC is a different approach, but there must still be a basic need for displaying data from multiple sources at the same time.
我可以看到,如果我用 @Model
然后将访问控制器中的数据集。但是,如果你想从2个或3个独立的项目显示数据是什么?
I can see that if I use @Model
then it will access the data set in the controller. But what if You want to display data from 2 or 3 separate items?
如果我想显示客户
,他们的地址和当前订单都在同一页上,有没有经过这3个独立的模式,以一个视图的方式,或者是它,我需要为每一个局部视图,然后显示他们都在同一页上的情况?
If I want to display a Customer
, their address and their current order all on the same page, is there a way of passing these 3 seperate models to the one view, or is it a case that I need to create a partial view for each, and then display them all on the same page?
推荐答案
有一个视图模型
它包含所有这些数据(类)作为属性并返回到您的视图
Have a ViewModel
which holds all those data(classes) as properties and return that to your view
public class CustomerViewModel
{
public int ID { set;get;}
public string Name { set;get;}
public Address Address{ set;get;}
public IEnumerable<Order> Orders { set;get;}
public CustomerViewModel()
{
if(Address==null)
Address=new Addres();
if(Orders ==null)
Orders =new List<Order>();
}
}
public class Address
{
public string AddressLine1 { set;get;}
//Other properties
}
public class Order
{
public int ORderID { set;get;}
//Other properties
}
您GET Action方法
your GET Action method
public ActionResult Index(int id)
{
var vm=new CustomerViewModel();
vm.Name=repo.GetUser(id).Name;
vm.Address=repo.GetAddressFromUserID(id);
vm.Orders=repo.GetOrdersFromUser(id);
return View(vm);
}
和您的视图将被强类型TP CustomerViewModel
And your View will be strongly typed tp CustomerViewModel
@model CustomerViewModel
<p>@Model.Name</p>
<p>@Model.Address.AddressLine1</>
@foreach(var item in Model.Orders)
{
<p>@item.OrderID</p>
}
这篇关于如何访问在剃刀视图的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!