2010-06-14 49 views
2

這看起來像模型綁定導致我的問題。Asp.Net MVC - 將參數綁定到模型值!

基本上我有一個稱爲ProductOption模型和用於此問題它有2個字段

ID的目的(INT)PK 的ProductID(INT)FK

我有一個標準路線建立

context.MapRoute(
     "Product_default", 
     "Product/{controller}/{action}/{id}", 
     new { controller = "Product", action = "Index", id = UrlParameter.Optional } 
    ); 

,如果用戶想增加一個選項的URL是,

/產品/選項/在上面的URL 1添加/ 1

是產品ID,我有以下的代碼返回一個空模型視圖,

[HttpGet] 
public ActionResult Add(int id) 
{ 
    return View("Manage", new ProductOptionModel() { ProductID = id }); 
} 

現在在我看來,我把一個隱藏字段

<%= Html.HiddenFor(x=>x.ID) %> 

這是用來確定(上提交),如果我們在編輯或添加新的選項。然而,.net中的模型聯編程序似乎用1(或URL中的id參數的值)代替.ID(當離開上述get actionresult時爲0)

我該如何停止或解決此問題?

視圖模型

public class ProductExtraModel 
{ 
    //Database 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public int ProductID { get; set; } 

    public ProductModel Product { get; set; } 
} 
+0

你的代碼暗示它在模型中被稱爲ProductID而不是.ID? – Andrew 2010-06-14 15:11:34

+0

你可以發佈視圖模型代碼嗎? – Andrew 2010-06-14 15:12:33

+0

@SocialAddict,完成。 – LiamB 2010-06-14 15:14:25

回答

2

我覺得id參數是由默認設置,因爲,你的路線設置它。在你的控制器裏面,你在ProductID的ViewModel中設置了一個額外的參數,這可能總是等於ID參數,因爲兩者基本都被設置爲QueryString/GET參數。 (在這種情況下爲1)。

你改變路線的修復工作,你從分配的ID參數阻止它似乎是一個不錯的選擇,但也許並不理想 - 這取決於你想如何解決這個問題:

context.MapRoute(
    "Product_addoptionalextra", 
    "Product/{controller}/Add/{ProductID}", 
    new { controller = "Product",action="Add", ProductID = UrlParameter.Optional } 
); 

另外,再爲了讓ID實際上是相關的ProductID,可以使用代表ID的OtherID。

我會建議解決這個問題,如果你有MVC 2的方式是使用EditorTemplates/DisplayTemplates。雖然我不知道你的ProductViewModel,但我認爲它裏面有ID。如果您設置了適當的模板,您幾乎可以忘記可能重疊的ID。

public class ProductExtraModel 
{ 
    //Database 
    public int ID { get; set; } 
    public string Name { get; set; } 

    [UIHint("Product")] 
    public ProductModel Product { get; set; } 
} 

您可以訪問時,該模型被傳遞迴使用productExtraViewModel.Product.ID控制器和您的正常ID仍可在productViewModel.Id產品ID。

0

我已經更新我的路線修正了這個(不completley喜歡它 - 但它的作品)

public override void RegisterArea(AreaRegistrationContext context) 
     { 
      context.MapRoute(
       "Product_addoptionalextra", 
       "Product/{controller}/Add/{ProductID}", 
       new { controller = "Product",action="Add", ProductID = UrlParameter.Optional } 
      ); 

      context.MapRoute(
       "Product_default", 
       "Product/{controller}/{action}/{id}", 
       new { controller = "Product", action = "Index", id = UrlParameter.Optional } 
      );   
     }