如何使用ViewModel访问asp mvc5中同一控制器和视图中不同模型的不同实体

时间:2017-09-07 10:06:56

标签: asp.net-mvc asp.net-mvc-5

我希望在设计和下拉列表项目中显示下拉列表,将从品牌模型的标题中获取。

设计模型

public class Design
{
    public int DesignId { get; set; }
    public string Title { get; set; }
    public string Desciption { get; set; }
    public int? price { get; set; }
    public bool Isdeleted { get; set; }
    public string AddedBy { get; set; }
    public DateTime? AddedDate { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime? UpdatedDate { get; set; }

    public int UserId { get; set; }

    //temp data 
    public string brandTitle { get; set; }
    //[MaxLength]
    public string pictureLocation { get; set; }
}

品牌模型

public class Brand
{
    public int BrandId { get; set; }
    public string Title { get; set; }
    public bool Isdeleted { get; set; }
    public string AddedBy { get; set; }
    public DateTime? AddedDate { get; set; }
    public string UpdatedBy { get; set; }
    public DateTime? UpdatedDate { get; set; }
}

设计控制器

public ActionResult Create()
    {
            return View();
    }

创建设计视图。

@model E_Darzi.Models.Design

@Html.EditorFor(model => model.brandTitle, new { htmlAttributes = new { @class = "form-control" } })

1 个答案:

答案 0 :(得分:1)

访问控制器中的数据并将其发送到视图

public ActionResult Index(){
    var data = db.DesignBrandsVM.Include(d=>d.Brand).ToList(); 
    returen view(data);
}

将值保存到不同的实体中 创建vm类

public class DesignBrandsVM
    {
        public int DesignId { get; set; }
        public string Title { get; set; }
        public string Desciption { get; set; }
        public int? price { get; set; }
        public bool Isdeleted { get; set; }
        public string AddedBy { get; set; }
        public DateTime? AddedDate { get; set; }
        public string UpdatedBy { get; set; }
        public DateTime? UpdatedDate { get; set; }


        public int BrandId { get; set; }
        public string Title { get; set; }
        public bool Isdeleted { get; set; }
        public string AddedBy { get; set; }
        public DateTime? AddedDate { get; set; }
        public string UpdatedBy { get; set; }
        public DateTime? UpdatedDate { get; set; }
    }

<强>控制器 在post方法中赋值并保存到db

    public ActionResult Create(DesignBrandsVM vm){
    var Design = new Design()
    {
        Title = vm.Title,
        Desciption = vm.Desciption,
        price = vm.price,
        Isdeleted = false
    };

    var Brand = new Brand()
    {
        Title = vm.BrandTitle,
        Isdeleted = false
    };

    db.Design.Add(Design);
    db.Brand.Add(Brand); 
    db.SaveChanges(); 
}