【问题标题】:How to initialise data model before insert in ASP.net FormView如何在插入 ASP.net FormView 之前初始化数据模型
【发布时间】: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


    【解决方案1】:

    这是一个老问题,但是:

    使用表单视图的 IntemInserting 方法。因此,要设置 TypeID,您可以执行以下操作:

    protected void FormView_ItemInserting(object sender, FormViewInsertEventArgs e)
    {
        e.Values["TypeId"] = TheDefaultValue;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 1970-01-01
      相关资源
      最近更新 更多