2010-06-14 60 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 } 
      );   
     }