Javascript – Asp.Net ViewState lost with RegisterClientScriptBlock

asp.netcjavascript

I am validating a zip code using Javascript that is generated server-side, and injected when a LinkButton is clicked. Then, I retrieve the return value by calling a server-side function when the page loads.

This works nicely, but the problem is that the ViewState is completely lost after PostBack. Below is the code, starting with the page_load event, the button click event, and then the callback called from the page_load event.

Is there a way I can somehow save the ViewState, maybe easily in a session variable? Or is there a workaround I can use?

// In Page_Load
if (Request.Form["__EVENTTARGET"] == "CallFunction") {
    GetValidateZipCodeScriptReturnValue(Boolean.Parse(Request.Form["__EVENTARGUMENT"].ToString()));
}

// OnClick for LinkButton
private bool ValidateZipCode(string zip) {
    StringBuilder script = new StringBuilder();
    script.Append("<script language='javascript' type='text/javascript'>");
    script.Append(@"var regex = /^\d{5}$|^\d{5}-\d{4}$/;");
    script.Append("__doPostBack('CallFunction', regex.test(" + zip + "));");
    script.Append("</script>");

    Type t = GetType();

    if (!ClientScript.IsClientScriptBlockRegistered(t, "ValidateZipCodeScript")) {
        ClientScript.RegisterClientScriptBlock(t, "ValidateZipCodeScript", script.ToString());
    }

    return false;
}

// Method called on PostBack to get the return value of the javascript
private void GetValidateZipCodeScriptReturnValue(bool valid) {
    m_ZipCode = uxZip.Text;

    if (valid) {
        Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}",
        ProductCode, ZipCode));
    }
    else {
        Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code.");
        SetupPostBackViewState();
        ScrollToZipCode();
    }
}

Best Answer

Why not just use the OnClick event of the LinkButton? Or, better yet, look into the CustomValidator control, since it looks like all you're trying to do is validate a zip code and that's exactly what a CustomValidator can do (you'll need to look at the ClientValidationFunction, which is where you want to put your regex test).