2011-05-22 52 views
8

我正在學習ASP.NET MVC 3並試圖創建一個由多個模型組成的視圖,這些模型由一個外鍵鏈接在一起。最終目標是將單個表單插入到所有數據庫表中。ASP.NET MVC 3多個模型到單一形式

問題是,我無法弄清楚爲什麼當我右鍵單擊創建窗體不是在cshtml文件中自動生成的視圖。自動生成的代碼有很多幫助,因爲我有很多連接在一起的表格,還有許多我必須驗證和插入的字段。如果無法自動生成表單,那麼完成此操作最有效/最優雅的方法是什麼?

這是我所擁有的簡化。

型號:

class Customer 
{ 
    [Key] 
    public UInt64 CustomerId { get; set; } 

    [Required(ErrorMessage = "Name is required.")] 
    [Display(Name = "Customer Name")] 
    [MaxLength(50)] 
    public string FullName { get; set; } 
} 

class CustomerAdditionalDetails1 
{ 
    [ForeignKey("Customer")] 
    public UInt64 CustomerId { get; set; } 

    [Required(ErrorMessage = "This info is required.")] 
    [Display(Name = "Customer Information")] 
    [MaxLength(50)] 
    public string SomeInfo { get; set; } 
} 

class CustomerAdditionalDetails2 
{ // same foreign key as CustomerAddtionalDetails1, but with different properties 
} 

class CustomerAdditionalDetails3 
{ // same foreign key as CustomerAddtionalDetails1, but with different properties 
} 

... 

public class CustomerModel 
{ 
    public Customer Customer { get; set; } 
    public CustomerAdditionalDetails1 CustomerAdditionalDetails1 { get; set; } 
    public CustomerAdditionalDetails2 CustomerAdditionalDetails2 { get; set; } 
    public CustomerAdditionalDetails3 CustomerAdditionalDetails3 { get; set; } 
    ... 
} 

控制器:

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

[HttpPost] 
public ActionResult Submit(CustomerModel customer) 
{ 
    return View(); 
} 

請幫幫忙!

回答

7

當您生成視圖時,您是否基於CustomerModel創建強類型視圖?如果您正在生成視圖,則不會在頁面中輸出任何值,因爲您的所有屬性都是對其他對象的引用。您需要模型中包含的實際值類型以供腳手架自動將其包含在視圖中。也就是說,您可以隨時將它們添加到視圖中,如下例所示。

另外我注意到你的控制器中你的GET方法沒有返回一個模型給視圖來渲染。如果你想有一個基於模型生成的視圖,那麼你需要傳遞你想讓它生成的對象。

@model MvcApplication3.Models.CustomerModel 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

<fieldset> 
    <legend>CustomerModel</legend> 
</fieldset> 
<ul> 
<li>@Model.Customer.FullName</li> 
<li>@Model.CustomerAdditionalDetails1.SomeInfo1</li> 
<li>@Model.CustomerAdditionalDetails2.SomeInfo2</li> 
</ul> 
<p> 
    @Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) | 
    @Html.ActionLink("Back to List", "Index") 
</p> 


public class CustomerController : Controller 
    { 
     public ActionResult Index() 
     { 
      CustomerModel customerModel = new CustomerModel() 
      { 
       Customer = new Customer() 
       { 
        FullName = "Dan" 
       }, 
       CustomerAdditionalDetails1 = new CustomerAdditionalDetails1() 
       { 
        SomeInfo1 = "Somewhere1" 
       }, 
       CustomerAdditionalDetails2 = new CustomerAdditionalDetails2() 
       { 
        SomeInfo2 = "Somewhere2" 
       }, 
       CustomerAdditionalDetails3 = new CustomerAdditionalDetails3() 
       { 
        SomeInfo3 = "Somewhere3" 
       } 
      }; 

      return View(customerModel); 
     } 
    }