2010-04-02 87 views
1

我在我的視圖中有以下代碼,但是,我可以看到我沒有控制器中的值。哪裏不對? 在我看來,如何發送和檢索控制器

<% 
    using (Html.BeginForm()) 
    {%> 
     <%=Html.TextBox("Addresses[0].Line1") %> 
     <%=Html.TextBox("Addresses[0].Line2")%> 
     <%=Html.TextBox("Addresses[1].Line1")%> 
     <%=Html.TextBox("Addresses[1].Line2")%> 

     <input type="submit" name="submitForm" value="Save products" /> 
     <% 
    } 
%> 

我班如下:

public class Customer 
{ 
    public string FirstName { get; set; } 
    public string Lastname { get; set; } 
    public List<Address> Addresses { get; set; } 
    public Customer() 
    { 
     Addresses = new List<Address>(); 
    } 
} 

public class Address 
{ 
    public int Line1 { get; set; } 
    public int Line2 { get; set; } 
} 

我的控制器如下:

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

    [HttpPost] 
    public ActionResult Index(Customer customer) 
    { 
     return View(); 
    } 

回答

0

您的ActionResult該參數名爲顧客,所以默認模型聯編程序將默認在表單中查找該名稱。我相信,如果你修改代碼以下面就應該把它撿起來:

<%=Html.TextBox("customer.Addresses[0].Line1") %> 
    <%=Html.TextBox("customer.Addresses[0].Line2")%> 
    <%=Html.TextBox("customer.Addresses[1].Line1")%> 
    <%=Html.TextBox("customer.Addresses[1].Line2")%> 
0

檢查,以確保您的看法是綁定到客戶模型。

此外,查看包含表單的網頁時,請查看View生成的源以查看字段是否正確命名。

最後,如果沒有以上的幫助,在你的索引行動像這樣改變參數:

public ActionResult Index(FormCollection form) 

那麼你可以使用調試器來檢查傳遞中的FormCollection對象,看看到底是什麼視圖正在向您發送。

+0

用表格我可以看到數據發送到控制器。我不想使用formcollection,因爲文本框是動態創建和刪除的。難道還有其他的方式嗎? – learning 2010-04-02 12:43:12

+0

這些值將被動態創建,在這種情況下,我認爲formcollection並不是最好的選擇? – learning 2010-04-02 12:49:19