Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 4.5 WebForms: do I (still) really have to specify all 3 templates in a FormView?

Investigating the new strongly-typed, model-binding approach within ASP.NET 4.5 WebForms:

In Scott Hanselman's example of WebForms model binding (amongst others) I've seen the use of a FormView that opens in "Edit" mode, containing a number of DynamicControls e.g.

<asp:FormView runat="server" ID="MyForm" ... DefaultMode="Edit">
  <EditItemTemplate>
    <asp:DynamicControl runat="server" ID="Field1" DataField="Field1" Mode="Edit" />
    <asp:DynamicControl runat="server" ID="Field2" DataField="Field2" Mode="Edit" />
  </EditItemTemplate>
</asp:FormView> 

In my situation, my FormView's ItemTemplate, EditItemTemplate and InsertItemTemplate will be identical, except the ItemTemplate's controls will be in "ReadOnly" mode.

Do I (still) really need to provide three near-identical copies of the template within the FormView?

I'm happy to use DynamicControls, but the team here will never go for the "3x copy-paste" approach seemingly required for the FormView, especially for our large templates.

I had thought that maybe:

  • the DynamicControls could get their "Mode" from the containing FormView?
  • I could use something other than a FormView to contain my DynamicControls?
  • Should I manage the DynamicControls' mode in code-behind to avoid template duplication?

Any examples/ideas?

like image 400
Merenzo Avatar asked Nov 08 '12 05:11

Merenzo


1 Answers

No, you don't have to specify all 3 templates. I've had the same scenario and this is my solution:

  • Set the default mode to the most often used mode
  • Then in code behind of the form manage the form mode
  • In code behind copy the template e.g. EditTemplate you handcoded to the other one you need

    protected void Page_Init()
    {
        var action = RouteData.Values["action"].ToString();
    
        switch (action)
        {
            case "add":
                personForm.ChangeMode(FormViewMode.Insert);
                this.Page.Title += " Add";
                break;
            case "edit":
                personForm.ChangeMode(FormViewMode.Edit);
                this.Page.Title += " Change";
                break;
            default:
                personForm.ChangeMode(FormViewMode.ReadOnly);
                break;
        }
    
        // Reuse inserttemplate for editing
        if (personForm.CurrentMode == FormViewMode.Edit)
        {
            personForm.EditItemTemplate = personForm.InsertItemTemplate;
        }
    
    }
    
like image 100
Neville Avatar answered Oct 02 '22 14:10

Neville