【问题标题】:Using the same template for edit and insert in a list view在列表视图中使用相同的模板进行编辑和插入
【发布时间】:2013-11-13 22:47:33
【问题描述】:

我正在使用 WebForms .NET 4.5 和 asp:ListView 和模型绑定。其中我使用的是:

<EditItemTemplate>
<InsertItemTemplate>

定义控件的外观。然而,99% 的时间这些布局是相同的。有没有一种方法可以同时用于 INSERT 和 EDIT?还是有另一种方法可以让我定义一次 HTML 并在其中使用它?

我没有使用&lt;asp:DynamicControl&gt;,而是正常使用&lt;asp:texbox&gt;等,所以我不相信.NET 4.5 WebForms: do I (still) really have to specify all 3 templates in a FormView?适用。

我已经尝试过用户控件。虽然内容被包含在内,但模型绑定被破坏,因为没有新值应用于正在插入/编辑的对象。

解决方案更新

声明没有插入模板的表单视图:

 <asp:FormView ID="fvData" runat="server"
        ItemType="DataLayer.Models.Country"
        DataKeyNames="Id"
        InsertMethod="InsertRecord"
        SelectMethod="BindData"
        UpdateMethod="UpdateRecord"
        OnDataBound="fvData_DataBound">
        <EditItemTemplate>
            <b>EDIT</b>   
            <div class="row">
                <div class="form-group">
                    <label class="col-md-4 control-label" for="txtCountryName">Name</label>
                    <div class="col-md-8">
                        <asp:TextBox runat="server" ID="txtCountryName" name="txtCountryName" placeholder="My Country" CssClass="form-control" Text='<%#: BindItem.Name %>'></asp:TextBox>
                        <dav:DataAnnotationsValidator CssClass="label label-danger" ID="davSchoolName" runat="server" ValidationGroup="Default" MetadataSourceID="msCountryInformation" ControlToValidate="txtCountryName" ObjectProperty="Name" Display="Dynamic" />
                    </div>
                </div>
            </div>
        </EditItemTemplate>
    </asp:FormView>

然后:

protected void Page_Init()
{
    if (!IsPostBack)
    {
        fvData.InsertItemTemplate = fvData.EditItemTemplate;
    }
}

您也在使用 EDIT 模板进行 INSERT。

【问题讨论】:

  • 如果您使用&lt;%# Bind("Path") %&gt; 而不是&lt;%# BindItem.Path %&gt;,用户控件会起作用吗?
  • @RichardDeeming 这是否意味着模型绑定将不再起作用,因为模型绑定需要使用 BindItem?
  • 我不这么认为。 AFAIK,任何一种语法都应该适用于模型绑定。
  • @RichardDeeming 尝试了 Bind() 语法并表现出与 BindItem 相同的行为,即。它显示数据,但不会将其更新回模型和数据库。

标签: c# model-binding asp.net-4.5


【解决方案1】:

最好的办法是为自己开发一个自定义的ListView

使用一个模板和init ListView 将那个模板用于另一个模板。您可能还需要自定义save 按钮以在任何模式下切换CommandName

此处提到的代码将引导您朝上述方向发展。

https://stackoverflow.com/a/2202850/1355315

我认为你的问题和这个帖子一样。

【讨论】:

  • 感谢@abhitalks 让我再次查看建议的解决方案。我以前看过它,尝试过它并因为它不起作用(即使用列表视图)而将其解雇。但是,使用 FormView 再次尝试它,根据我更新的原始帖子,它就像一个魅力。
【解决方案2】:

也许您应该将此通用布局提取为单独的控件。我在 ASP.Net MVC 中执行此操作。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-21
  • 2016-06-17
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
相关资源
最近更新 更多