简体   繁体   English

Asp.Net ViewState丢失与RegisterClientScriptBlock

[英]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. 我正在使用服务器端生成的Javascript验证邮政编码,并在单击LinkBut​​ton时将其注入。 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. 这很好用,但是问题是ViewState在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. 下面是代码,从page_load事件,按钮click事件开始,然后是从page_load事件调用的回调。

Is there a way I can somehow save the ViewState, maybe easily in a session variable? 有什么方法可以保存ViewState,也许可以轻松地保存在会话变量中吗? 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 ? 为什么不只使用LinkButtonOnClick事件? 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). 或者,更好的是,查看CustomValidator控件,因为您似乎要尝试验证邮政编码,而这正是CustomValidator可以做的(您需要查看ClientValidationFunction ,在这里想要进行正则表达式测试)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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