2017-04-06 33 views
0

我想在同一視圖中顯示用戶信息和地址模型。如何使用實體框架插入並顯示用戶和地址模型

這是我的代碼結構:

在數據訪問層,我的模型類:

User.cs

public class User 
{ 
     [Key] 
     public int UserId { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string RestaurantName { get; set; } 
     public string PrimaryPhone { get; set; }  
} 

Location.cs

public class Location 
{ 
      public int Id { get; set; } 
      public string Line1 { get; set; } 
      public string Line2 { get; set; } 
      public string City { get; set; } 
      public string State { get; set; } 
      public string Country { get; set; } 
      public string ZipCode { get; set; } 
      public User User { get; set; } 
} 

因此,我有兩個獨立的存儲庫,用於執行添加和獲取所有功能的用戶和地址模型,這些功能工作得非常好。

現在,我希望這兩個模型信息應同時顯示在視圖中。

如何在同一視圖中組合兩者。我無法做到。我可以做到,但事情都是在不同的視圖中顯示。

任何意見將不勝感激!

+0

爲什麼不創建ViewModel類並傳遞整個類或ViewModel類的列表? – ViVi

+0

是的,我可以通過VIew Model課程。但我的問題是我有兩個存儲庫,像UserRepo和AddressRepo,它分別插入數據。 Siding ViewModel,我可以結合顯示模型。但問題是,如何在兩個獨立的存儲庫中傳遞此視圖以將數據保存在數據庫中。 – Marshall

+0

爲什麼不使用ajax回發到控制器並將數據保存到2個存儲庫? – ViVi

回答

1

使用ViewModel。您的ViewModel可能如下所示:

public class MyViewModel 
{ 
    public User UserVm {get;set;} 
    public Location LocationVm {get;set;} 
} 

在您的視圖中使用MyViewModel。你的控制器將接受一個MyViewModel對象。

然後,您可以將LocationVm和UserVm對象從viewModel傳遞到您的存儲庫。

+0

那麼,如何通過它。當我嘗試這樣做時,我得到以下異常:「不能隱式地將System.Collection.Generic.list 轉換爲Projectname.Data.Models。用戶 – Marshall

+0

我將視圖模型從用戶和位置更改爲IEnumerable 和IEnumerable 。所以當我這樣做的時候,這個錯誤會發生,但是我會考慮另一個問題。鑑於它說**「原型不包含定義,並且沒有擴展方法接受在mvc中查看類型Iprincipe的第一個參數」** – Marshall

+0

通過爲索引視圖創建單獨的視圖模型並創建視圖來解決此問題。現在,我可以收集信息。但在接收數據時遇到問題。 – Marshall

1

增加一個屬性與您的用戶模型像下面

- 模型部分

public class User 
{ 
public List<Location> location {get;set;} 
} 

- 控制器部分

public ActionResult Index() 
{ 
List<Location> loc= new List<Location>() { new Location{ City = "one" }, new 
Location{ City = "two" } }; 

List<User> user= new List<User>() { new User{ FirstName = "A", location = 
loc }, new User{ FirstName = "B" } }; 

return View(user); 
} 

- 視圖部分

@model IEnumerable<YourSolutionName.Models.User> 

@foreach (var item in Model) 
{ 
<tr> 
    <td> 
     @Html.DisplayFor(modelItem => item.FirstName) 

     @{ 
      if (item.location != null) { 
     foreach(var i in item.location) 
     { 
      <h1>@i.City</h1> 
     } 
     } 
    } 
} 

這是一個通過使用方法,我們可以在同一視圖上使用兩種不同的模型。

至於演示我添加了靜態值,您可以使用您的上下文對象添加動態。 它可能會幫助你。謝謝

+0

感謝您提供詳細信息。我能夠綁定視圖模型中的數據。但是當我點擊創建時,viewmodel沒有獲取數據,它獲得了空值。我不明白什麼是錯的 – Marshall

+0

我的意思是你試圖說,你需要發佈(發送)數據到Controller.Is它是正確的嗎? –

+0

是的,現在我可以成功地將數據插入數據庫。但是,我無法在索引視圖中查看它。我可以知道如何去做。當我使用上面的UserViewModel它給了我以下錯誤:**「不能隱式轉換System.Collection.Generic.list 到Projectname.Data.Models.User」** – Marshall