I have created a simple FormView in ASP.net 4.5
<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>
I would like to be able to pre-populate some of the fields (e.g. TypeId in the above example) so that a complete model is returned to InserItem() method, and also because pre-populating some fields improves/helps the user experience (common default values for example). I had thought/hoped that the FormView's SelectMethod would do this, but apparently it doesn't.
// 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);
}
}
I could, I suppose, initialise the controls on the form directly, but this seems cumbersome.
Does anyone know if there is a solution to this?
This is an old question but:
Use the form view IntemInserting method. So, to set TypeID you would do something like:
protected void FormView_ItemInserting(object sender, FormViewInsertEventArgs e)
{
e.Values["TypeId"] = TheDefaultValue;
}