简体   繁体   中英

Asp.Net ViewState lost with RegisterClientScriptBlock

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();
    }
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM