2012-10-30 148 views
0

我有一个webforms项目,我在ASP.NET 4.5上使用新的模型绑定。我在我的页面上有一个强类型的FormView,它包含一个DropDownList,它允许用户选择一个相关的实体(想象产品 - >类别)。Webforms模型绑定和复杂类型

有没有一种方法来设置它,以便在我的InsertMethod上,我可以直接访问相关的实体(例如Product.Category)?我需要检查相关实体上的一些验证规则,而我发现要做的唯一方法是设置我的DropDownList以返回相关记录的Id,然后从数据库中获取它。这似乎相当低效。

编辑:该死的,没人啊!那么,这就是你成为新技术的早期采用者所得到的结果! :D

回答

0

我对MVC有同样的问题,我发现的最好的解决方案是在我的模型上使用ForeignKey数据注释,这样我可以只插入相关对象的ID并在稍后检索对象。这里有一个例子:

public class Product { 
    public int ProductId { get; set; } 
    public string Name { get; set; } 
    // Add this field so I can add the entity to the database using 
    // category id only, no need to instantiate the object 
    public int CategoryId { get; set; } 

    // Map this reference to the field above using the ForeignKey annotation 
    [ForeignKey("CategoryId")] 
    public virtual Category Category { get; set; } 
} 

public class Category { 
    public int CategoryId { get; set; } 
    public string Name { get; set; } 
} 

现在,它一直年龄,因为我最后一次使用的WebForms,所以我真的不知道该怎么类别列表绑定到DropDownList的,也许是这样的:

<asp:DropDownList ID="CategoryId" SelectMethod="GetCategories" runat="server" /> 

也许当你的产品返回到你的创建或更新方法时,它会随着CategoryId属性的正确归属而出现,然后你所要做的就是保存EF的上下文。祝你好运。