2012-03-18 47 views
1

假設我有兩個類(產品&產品搜索)具有相同屬性「標題」ASP MVC不同類型的3綁定模型

如果我在表單中有一個領域:

<input type="textbox" name="Product.Title" id="Product_Title"/> 

我可以使用控制器將它綁定:

public ActionResult Search(Product product) 

但有什麼辦法,以便它綁定到我可以指定綁定的參數:

public ActionResult Search(ProductSearch productSearch) 

我試過[Bind(Prefix = "Product")]無濟於事。

回答

1

[Bind(Prefix = "Product")]應該工作。例如:

型號:

public class ProductSearch 
{ 
    public string Title { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    [HttpPost] 
    public ActionResult Index([Bind(Prefix = "Product")]ProductSearch productSearch) 
    { 
     return Content(productSearch.Title); 
    } 
} 

查看:

@using (Html.BeginForm()) 
{ 
    <input type="text" name="Product.Title" id="Product_Title" /> 
    <button type="submit">OK</button> 
} 
+0

感謝您抽出時間回覆,但它並沒有解決我的問題我問道。我有一個解決上述問題的方法,即從輸入中刪除產品前綴,但我仍然很想知道上述情況是否可以獲得。 – Rob 2012-03-18 11:14:20

+0

@DrRob,是的,它是可以獲得的,這是我的答案的第一部分地址。 – 2012-03-18 12:01:50

+0

這並不意味着我必須改變這一行 to 這正是我不想做的事 – Rob 2012-03-18 12:03:46