Webforms模型绑定和复杂类型

时间:2012-10-30 13:23:05

标签: c# webforms model-binding

我有一个webforms项目,我在ASP.NET 4.5上使用了新的Model Binding。我的页面上有一个强类型的FormView,它包含一个DropDownList,允许用户选择一个相关的实体(想想Product - > Category)。

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

编辑:该死的,没有人啊!?嗯,这就是你成为新技术的早期采用者所获得的! :d

1 个答案:

答案 0 :(得分: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" />

也许当你的产品重新使用你的Create或Update方法时,它会附带正确归属的CategoryId属性,然后你所要做的就是保存EF的上下文。祝你好运。