【问题标题】:How to call javascript (or jQuery) on page load (update/change) in ASP.NET如何在 ASP.NET 中的页面加载(更新/更改)时调用 javascript(或 jQuery)
【发布时间】:2016-07-08 20:30:37
【问题描述】:

我有创建一些对象的页面。在此页面上,如果用户选中复选框,将出现带有一些文本字段的隐藏区域。然后当用户尝试提交对象时,服务器可以发送验证错误,因此用户需要更正一些字段。问题是,当这种情况发生时,带有附加字段的区域会再次隐藏(但复选框已选中,因此用户需要取消选中然后再次选中)。那么是否可以在每次发生变化或服务器向我发送错误时调用此函数? 为了显示和隐藏附加部分,我使用了这个 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 中为正文标签或类似的东西调用此类函数是否是一种好习惯......

【问题讨论】:

    标签: javascript c# jquery asp.net razor


    【解决方案1】:

    当您的部分页面加载时,您可以使用 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);
       }
    }
    

    【讨论】:

    • 我应该把它放在哪里? (我在项目中使用 MVC 模式)
    猜你喜欢
    • 2012-04-10
    • 1970-01-01
    • 2011-05-15
    • 2020-03-27
    • 2017-06-20
    • 1970-01-01
    • 2019-11-30
    • 2015-03-29
    • 2015-11-13
    相关资源
    最近更新 更多