ViewStateMode is a great addition to ASP.NET 4.0

by Scott 1. July 2010 13:27

I've never paid much attention to ViewState, but it's a pretty cool thing.  It is a technique used by an ASP.NET Web page to persist changes across postbacks.  Before posting back, all your data is stored in a hidden form field called __VIEWSTATE.  That way when the page is rebuilt, your dropdown, textbox, label, etc data will still be there.  You can read more in depth here, but it's just always worked and I haven't had concern for the huge payload that it can sometimes bring.  Maybe that's why my bandwidth usage on my old e-commerce site is out of control! 

Well now I'm paying attention and ASP.NET 4.0 gives us a new tool to help control ViewState, the ViewStateMode property.  Say I have a dropdown where I select the quantity of a product that I want to buy.  I then click "Add to Cart".  Well, what happens when I click that button is that the page rebuilds itself and the code on my "Add to Cart" button is run.  If I have ViewState turned off for my dropdown, when it comes time for run the "Add to Cart" code, the dropdown won't have any items in it!  In fact, this happened to me today and I realized that I had ViewState turned off.  By default, ViewStateMode is set to "Inherit", so all my child controls, including the quantity drop down wasn't saving it's values in ViewState.  A simple change of the ViewStateMode property to "Enabled" fixes the problem and everything is happy.

See for yourself here in this sample project

Markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestViewState.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="pnlViewState" runat="server" ViewStateMode="Disabled">
            <asp:DropDownList ID="DropDownList1" runat="server" ViewStateMode="Enabled" />
            <asp:Button ID="Button1" runat="server" Text="Postback" OnClick="Button1_Click" />
        </asp:Panel>
    </div>
    </form>
</body>
</html>

Code Behind:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestViewState
{
    public partial class Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DropDownList1.Items.Add(new ListItem("1", "1"));
                DropDownList1.Items.Add(new ListItem("2", "2"));
                DropDownList1.Items.Add(new ListItem("3", "3"));
                DropDownList1.Items.Add(new ListItem("4", "4"));

                DropDownList1.SelectedIndex = 2;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            DropDownList1.SelectedIndex = 3;
        }
    }
}

 

By enabling ViewStateMode on my dropdrown list, it persists the values so that they are available when posting back.   To test this out, set ViewStateMode="Disabled" on the dropdown list and set a breakpoint on the Button1_Click event.  Then run the project.  Click the postback button and you'll see that DropDownList1 doesn't have anything in it!  Change back to "Enabled" and you'll see everything works.

By setting the ViewState on individual controls, you can really cut down on your payload on each postback.  This is a great addition in ASP.NET 4.0

Get the code for this project here:

TestViewState.zip (19.98 kb)

Tags:

ASP.NET 4.0

Special characters in xaml

by Scott 17. May 2010 12:48

Here is a quick chart for displaying special characters in xaml

<    &lt;

>    &gt;

&    &amp;

"    &quot;

Tags:

Silverlight

BlogEngine 1.6.1

by Scott 30. April 2010 05:44

Spam.  I hate spam.  I get dozens of spam comments a day.  While searching for spam control for this blog, I found that a new version just came out and recaptcha was added!  Hooray!  I followed the directions and recaptcha is now added to the comments page.  I hope this works!

I need a good looking theme!  Anybody have some good ones that work with 1.6.1?

Don't have a blog, get BlogEngine.NET here

Tags:

Visual Studio color schemes

by Scott 29. April 2010 09:16

You may have seen this on ScottGu's blog, but here is a link to a great collection of Visual Studio color schemes.  I will never understand the black background ones..those take me back to my days working on "green" screens.  Ugly times.

http://studiostyles.info/

Tags:

Bookpool.com returning?

by Scott 21. April 2010 16:20

site says relaunching soon!

http://www.bookpool.com/

Tags:

Books

ASP.NET 4.0 URL routing 404 problems with IIS7

by Scott 21. April 2010 13:15

As I described before, I love the new routing feature in ASP.NET 4.0.  I succesfully converted my code from Intelligencia over to the built in routing.  The site ran great locally, but when I deployed to IIS7, I got 404's on every page that didn't have an extension.  Those pages were my routed product pages.

Some googling led to to add a line to my web.config file.  Here is is:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>

This apparently forces IIS to invoke the routing module.  I found no mention of this anywhere and was under the assumption I didn't have to modify any config files.  Hope this helps somebody.

Here are some sources where I found this:

http://forums.asp.net/t/1523639.aspx
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx

Tags:

SEO

ASP.NET 4.0 URL routing

by Scott 21. April 2010 13:07

I was reading ScottGu's blog the other day and decided to give the new URL routing in ASP.NET 4.0 a try.  Got it to work great, just register the routes in global.asax and then pull out the data on the page where you need it.

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RegisterRoutes(RouteTable.Routes);
        }

        void RegisterRoutes(RouteCollection routes)
        {
            routes.MapPageRoute("product-browse", "product/{name}_{id}", "~/Product.aspx");
            routes.MapPageRoute("category-browse", "category/{name}_{id}", "~/CategoryPage.aspx");
            routes.MapPageRoute("brand-browse", "brand/{name}_{id}", "~/BrandPage.aspx");
            routes.MapPageRoute("search", "search/{*searchTerms}", "~/Search.aspx");
        }

Above, I registered a route called product-browse where a page like http://mysite.com/product/some-great-toy_12 will get mapped to my Product.aspx page.  Inside Product.aspx, you would just need to retrive your id (and the name if you need it)

         string name = Page.RouteData.Values["name"] as string;
         int productId = Convert.ToInt32(Page.RouteData.Values["id"]);

Now, I have the productId, pulled right off the URL without using querystrings like I've used in the past.

I like it!

 

Tags:

SEO

ClientIDMode in ASP.NET 4.0

by Scott 19. April 2010 07:05

I have some CSS that was set up for me by a graphics artist.  One of CSS elements is an ID that is used to format a <div> tag all nice and pretty.  I decided I needed to manipulate this <div> through code, so I thought I would change it to an <asp:Panel> as I've done in the past.  The problem I found was that the panel control has a property called CssClass, where you can specify some css to use, but what if I wanted to use my existing css ID and not a css class?  Confused about the difference, check this out.

The problem is that ASP.NET will auto generate your control ID's and the ID is what needs to be specified in order to use my css!  If I change my <div> to a <asp:Panel>, the ID will be generated something like:

<div id="MainContent_productImage">

It prefixes the ID with the parent container, in this case, a MainContent div.  Well, I want the ID to be productImage so my styling is applied.

In ASP.NET 4.0, there is a new ClientIDMode property.  I set the ClientIdMode to "Static" and I get the exact ID I want.  That is,

 <asp:Panel id="productImage" runat="server" ClientIDMode="Static">

will render out as:

<div id="productImage">

I get the benefit of manipulating the <div> in code behind before it's rendered AND I get to keep the ID I want!

I could go into a long tuturial here, but Rick Strahl has an excellent-as-always post here

Here's an MSDN link

Tags:

CSS

CSS Tip : Image Borders

by Scott 19. April 2010 06:04

Who wants the ugly default border around an image? 

Instead of adding: 

style="border: none"

to every image, just add:

a img { border: none;}

to one of your css files.

I can't believe how simple this is.  CSS is not one of my strengths, but as I work more and more, I find great tips that make my site look great.

Scott

Tags:

CSS

Using Fiddler with ASP.NET and FireFox

by Scott 18. April 2010 16:41

I attempted today to use Fiddler with firefox to debug my asp.net web site on my local developer machine.  I was greeted with:

[Fiddler] Connection to localhost failed.
Exception Text: No connection could be made because the target machine actively refused it ::1:11973

After messing with many of Fiddler's options, I found that by unchecking the "Enable IPv6 (if available)" option, traffic was once again flowing through Fiddler.  I am running Windows 7 64 bit with Visual Studio 2010.

 

Hope this helps somebody,

Scott

 

Tags:

General

About the author

Hi, I'm Scott.  My company develops in C#/ASP.NET/Silverlight and and creates e-commerce web sites for small business.  Visit our corporate site, Gildner Solutions.  We are working on a brand new one now.

RecentComments

Comment RSS