简体   繁体   English

Webforms模型绑定和复杂类型

[英]Webforms Model Binding and Complex Types

I have a webforms project and I'm using the new Model Binding on ASP.NET 4.5. 我有一个webforms项目,并且正在ASP.NET 4.5上使用新的模型绑定。 I have a strongly typed FormView on my page that contains a DropDownList that will allow the user to select a related entity (think Product -> Category). 我的页面上有一个强类型的FormView,其中包含一个DropDownList,该列表允许用户选择一个相关实体(例如Product-> Category)。

Is there a way to set this up so that, on my InsertMethod, I can get direct access to the related entity (Product.Category, for example)? 有没有一种方法可以进行设置,以便在我的InsertMethod上可以直接访问相关实体(例如Product.Category)? I need to check some validation rules on the related entities, and the only way I found to do that was to set up my DropDownList to return the Id of the related record, and then fetch it from the database. 我需要检查有关实体的一些验证规则,而我发现这样做的唯一方法是设置我的DropDownList以返回相关记录的ID,然后从数据库中获取它。 That seems rather inefficient. 这似乎效率很低。

Edit: Damn, no one huh!? 编辑:该死,没人吧!? Well, that's what you get for being an early adopter of new technologies! 好吧,这就是您成为新技术的早期采用者所得到的! :D :D

I had the same issue on MVC, the best solution I have found was to use the ForeignKey data annotation on my model, this way I could insert only the related object's ID and retrieve the object later. 我在MVC上遇到了同样的问题,发现的最佳解决方案是在模型上使用ForeignKey数据注释,这样我就可以只插入相关对象的ID,然后再检索该对象。 Here's an example: 这是一个例子:

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; }
}

Now, it's been ages since I last used WebForms so I don't really know how to bind the categories list to the DropDownList, maybe something like this: 现在,自上次使用WebForms以来已经有很多年了,所以我真的不知道如何将类别列表绑定到DropDownList,也许是这样的:

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

And maybe when you get your product back on your Create or Update method, it will come with the CategoryId property properly attributed, and then all you'll have to do is save the EF's context. 也许当您将产品恢复为Create或Update方法时,它将带有正确属性的CategoryId属性,然后您要做的就是保存EF的上下文。 Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM