Server Controls in ASP.NET MVC without ViewState
Introduction :
ASP.NET Web Forms provides a development environment just like GUI or windows application and try to hide statelessness nature of HTTP protocol. For accomplishing this target, Web Forms uses ViewState (a hidden field) to remove the gap between HTTP statelessness and GUI applications. But the problem with this technique is that ViewState size which grows quickly and also go back and forth with every request, as a result it will degrade application performance. In this article i will try to use existing ASP.NET server controls without ViewState.
Description :
When you add a server control which needs viewstate, in the presentation view in ASP.NET MVC application without a form tag, for example,
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
It will shows the following exception,
Control 'TextBox1' of type 'TextBox' must be placed inside a form tag with runat=server
When you place this textbox inside a form tag with runat=server, this will add the following ViewState even when you disable ViewState by using EnableViewState="false"
<input type="hidden" value="/wEPDwUJMjgzMDgzOTgzZGQ6u9CwikhHEW39ObrHyLTPFSboPA==" id="__VIEWSTATE" name="__VIEWSTATE"/>
The solution to this problem is to use the RenderControl method of server control which is simply renders HTML without any ViewState hidden field.
<% TextBox txt = new TextBox();
txt.Text = "abc";
StringBuilder sb = new StringBuilder();
System.IO.StringWriter textwriter = new System.IO.StringWriter(sb);
HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);
txt.RenderControl(htmlwriter); %>
<%= sb.ToString() %>
This will render <input type="text" > without any View State. This technique become very useful when you are using rich server controls like GridView. For example, let's say you have List of Recalls in Model.Recalls, then you will show your tabular data as,
<% GridView gv = new GridView();
gv.AutoGenerateColumns = true;
gv.DataSource = Model.Recalls;
gv.DataBind();
StringBuilder sb = new StringBuilder();
System.IO.StringWriter textwriter = new System.IO.StringWriter(sb);
HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);
gv.RenderControl(htmlwriter);%>
<%= sb.ToString() %>
This code might looks odd in your presentation view. A more better approach is to create a HTML Helper method which contains the above code.
Summary :
In some cases you might needs to use existing ASP.NET Web Forms server controls but also dislikes ViewState. In this article i try to solve this gap by using the RenderControl method of Control class. Hopefully you enjoyed and become ready to create HTML helpers for many of the existing server controls.