Automatically set a property value for a new record in a Dynamic Data application

喜你入骨 提交于 2019-12-13 05:14:08

问题


I have a SalesOrderItem table, and it has a UnitPrice column in case the salesperson wishes to override the unit price of the Product for that order item.

In an ASP.NET Dynamic Data application, what would be the best way to set that UnitPrice property on a new SalesOrderItem based on the standard UnitPrice for the product? In other words, when the user clicks New on the 'Items' screen for a sales order, the UnitPrice field should already be filled in with the normal unit price for the product.


回答1:


If the UnitPrice default value was a constant, it would be as simple as setting the DefaultValueAttribute on the UnitPrice metadata column. Since the default value must be calculated at runtime, we have to take a different approach.

It is not clear from the question how the Product record is located. Assuming it is available on the server when the Insert page is initially rendered, you could create a field template for the UnitPrice column. For the sake of example, let's also assume that the column type of UnitPrice is decimal.

Locate the field templates folder (by default in "~/DynamicData/FieldTemplates"). Using the Decimal_Edit.ascx* files as a guide, create a new set of field template files labeled "UnitPrice_Insert.ascx", "UnitPrice_Insert.ascx.cs", and "UnitPrice_Insert.ascx.designer.cs". Use the code-behind file to calculate and set the default value:

protected void Page_Init(object sender, EventArgs e) {
    decimal defaultUnitPrice;
    // Calculate and set the defaultUnitPrice here.
    // "this.Page" might be useful for locating the Product record.
    FieldValue = defaultUnitPrice;
}

Finally, annotate the metadata for the UnitPrice column to use the template that was just created:

[UIHint("UnitPrice")]

Now the Insert screen will use "UnitPrice_Insert.ascx" and thereby show the calculated default value, while the List, Details, and Edit screens will still use the "Decimal.ascx" and "Decimal_Edit.ascx" templates, which show the actual column value, not the default value.



来源:https://stackoverflow.com/questions/3538234/automatically-set-a-property-value-for-a-new-record-in-a-dynamic-data-applicatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!