2 ASP.NET MVC中的ViewModel

时间:2015-05-29 06:55:07

标签: c# asp.net-mvc kendo-ui

型号:

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

1 个答案:

答案 0 :(得分: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)
    }
}

然后在您的Kendo网格中,使用您的复合视图模型(在上面的示例中称为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}");  
})