2015-05-29 162 views
4

型號:2視圖模型在ASP.NET MVC

public class Order 
{ 
    [ScaffoldColumn(false)] 
    public int Id { get; set; }   

    public string UserName { get; set; }  

    public int Amount { get; set; }  

    [ScaffoldColumn(false)] 
    public Guid UniqueId { get; set; } 

    public DateTime CreateDate { get; set; } 

    public string ManagerId { get; set; }  

} 

public class UserProfile 
{ 
    public int Id { get; set; } 

    public string Username { get; set; } 

    public string Phone { get; set; } 

    [StringLength(255)] 
    public string NameSurname { get; set; } 

    public bool IsCompany { get; set; } 
} 

我需要Kendo Grid顯示2種型號。視圖中的示例代碼:

@(Html.Kendo().Grid<oko.Models.OrderDto>().Name("NewOrders").Columns(columns => 
{  
    columns.Bound(s => s.Username); 
    columns.Bound(s => s.NameSurname); 
    columns.Bound(s => s.Phone); 
    columns.Bound(s => s.CreateDate).Format("{0:dd/MM/yyyy}"); 
}) 

字段UserName它們具有相同。 如何通過字段PhoneNameSurname

回答

3

您不能綁定到多個類類型,所以最好的方法是創建一個複合類ViewModel來保存您需要的屬性。將其填充到控制器中,並將其傳遞迴模型。

實施例視圖模型

public class OrderDtoViewModel 
{ 
    public string UserName { get; set; } 
    public string NameSurname { get; set; } 
    public string Phone { get; set; } 
    public DateTime CreateDate { get; set; } 

    //etc... 
} 

控制器

public class MyController 
{ 
    public ActionResult Index() 
    { 
     var data = _myRepository.GetYourData(); 

     var viewModel = new OrderDto() 
     { 
      UserName = data.UserName, 
      NameSurname = data.NameSurname, 
      Phone = data.Phone, 
      CreateDate = data.CreateDate 
     }; 

     return View(data) 
    } 
} 

然後在您劍道格,用你的複合視圖模型(稱爲OrderDtoViewModel上面的例子)

@(Html.Kendo().Grid<oko.Models.OrderDtoViewModel>().Name("NewOrders").Columns(columns => 
{  
    columns.Bound(s => s.Username); 
    columns.Bound(s => s.NameSurname); 
    columns.Bound(s => s.Phone); 
    columns.Bound(s => s.CreateDate).Format("{0:dd/MM/yyyy}"); 
})