如何在 ASP.NET 页面加载(更新/更改)时调用javascript(或jQuery)

How to call javascript (or jQuery) on page load (update/change) in ASP.NET

本文关键字:更改 调用 javascript jQuery 更新 NET ASP 加载      更新时间:2023-09-26

我有创建某个对象的页面。在此页面上,如果用户选中复选框,将显示带有一些文本字段的隐藏区域。然后,当用户尝试提交对象时,服务器可以发送验证错误,因此用户需要更正某些字段。问题是,当发生这种情况时,具有其他字段的区域将再次隐藏(但是复选框被选中,因此用户需要取消选中,然后再次选中)。那么是否可以在每次发生更改或服务器向我发送错误时调用此函数?为了显示和隐藏其他部分,我正在使用以下jQuery代码:

function changeVisibilityOfCreateCustomerSection() {
            if ($("#isnewcustomer").prop("checked") == true) {
                $(".saf-createcustomersection > div > input").prop("disabled", false);
                $(".saf-createcustomersection").show();
            } else {
                $(".saf-createcustomersection > div > input").prop("disabled", true);
                $(".saf-createcustomersection").hide();
            }
        }

我是这样称呼它的:

@Html.EditorFor(model => model.isNewCustomer,
                        new { htmlAttributes = new {
                            @class = "checkBox",
                            onchange = "changeVisibilityOfCreateCustomerSection();",
                            id = "isnewcustomer" } })

我试图在javascript标签中使用这样的东西:

$(document).ready(function () {
            changeVisibilityOfCreateCustomerSection();
        });
        $(window).load(function () {
            changeVisibilityOfCreateCustomerSection();
        });

但是这些功能根本不起作用。我应该说页面是部分的,正文标签在共享布局中,所以我不确定在 onload 中调用此类函数对于正文标签或类似的东西是否是一种好习惯......

加载部分页面时,您可以使用Page_Load执行以下操作:

protected void Page_Load(object sender, EventArgs e){
   // checks here if the page is loaded normally not with a submission to the server from the same page
   if(!IsPostBack){
      ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "functionName()", true);
   }
}