【发布时间】:2014-04-08 09:12:57
【问题描述】:
我在 ASP.net 4.5 中创建了一个简单的 FormView
<asp:FormView runat="server"
ItemType="Wms.Models.GuiComponent"
DataKeyNames="GuiComponentId"
DefaultMode="Insert"
SelectMethod="GetItem"
InsertMethod="InsertItem"
RenderOuterTable="false">
<InsertItemTemplate>
<div class="form-container">
<asp:HiddenField runat="server" ID="TypeId" Value="<%# BindItem.TypeId %>"/>
<div class="row">
<asp:Label runat="server" AssociatedControlID="Reference">Reference</asp:Label>
<asp:TextBox runat="server" ID="Reference" TextMode="SingleLine" Text="<%# BindItem.Reference %>" />
</div>
<div class="controls margin-top-05">
<asp:Button ID="btnSubmit" Text="Create" CommandName="Insert" ValidationGroup="GuiComponent" runat="server" />
</div>
</div>
</InsertItemTemplate>
</asp:FormView>
我希望能够预填充一些字段(例如上面示例中的 TypeId),以便将完整的模型返回给 InserItem() 方法,并且因为预填充一些字段可以改进/帮助用户体验(例如常见的默认值)。我曾想过/希望 FormView 的 SelectMethod 会这样做,但显然它不会。
// This method is not called for the InsertItemTemplate
public GuiComponent GetItem()
{
return new GuiComponent
{
// Initialise properties here
TypeId = GuiType.GuiComponentTypeId
};
}
public void InsertItem()
{
var model = new GuiComponent();
try
{
TryUpdateModel(model);
if (ModelState.IsValid)
{
GuiComponentService.Insert(model);
UnitOfWork.SaveChanges();
var url = String.Format("../../ComponentDetail.aspx?id={0}",
model.GuiComponentId);
Response.Redirect(url, false);
}
}
catch (DbEntityValidationException dbException)
{
ModelState.AddException(dbException);
}
catch (Exception ex)
{
ModelState.AddException("", ex);
}
}
我想,我可以直接初始化表单上的控件,但这似乎很麻烦。
有没有人知道有没有办法解决这个问题?
【问题讨论】:
标签: asp.net data-binding formview