编程语言
首页 > 编程语言> > c# – 如何避免在ASP.NET代码隐藏中编写混乱的JavaScript?

c# – 如何避免在ASP.NET代码隐藏中编写混乱的JavaScript?

作者:互联网

我在质疑使用Javascript和ASP.NET的最佳做法是什么.

我不知道这是最好的做法,但我在codebehind中添加了javascript客户端事件.它工作正常,但这是最好的做法吗?

例如,我有一个单选按钮控件,我在Page_Init中添加了Javascript客户端事件.可以多次调用页面init,因此每次调用Page_It时都会呈现Javascript.

此外,很难调试长Javascript字符串.如何更干净……有办法吗?

让我们看一个包含Javascript的变量的示例:

scripts.Text += "<script type='text/javascript'>function ValidateDdl" + metachamp.ID +
"(sender, args) {  if(" + txtReason.ClientID + ".GetText() != '' ||" +
dynamicControl.ClientID +
".style.display == 'none' || HiddenFieldSaveError.Contains('" + metachamp.ID +
"') ){" + dynamicControl.ClientID + ".className='';HiddenFieldError.Remove(" +
metachamp.ID + ");" + errorImage.ClientID +
".SetClientVisible(false);args.IsValid = true;}else{var comboVal = document.getElementById('" +
Image9.ClientID + "'.substring(0,'" + Image9.ClientID +
"'.length - 6) + 'ddl').value ;if (comboVal != '0' ) {args.IsValid = true;HiddenFieldError.Remove(" +
metachamp.ID + ");" + validImage.ClientID +
".SetClientVisible(false);HiddenField.Remove('Bypass-' + '" +
metachamp.ID.ToString() + "');HiddenFieldSaveError.Remove(" + metachamp.ID +
");" + dynamicControl.ClientID + ".className='';" + errorImage.ClientID +
".SetClientVisible(false);}";

解决方法:

第一步是将JavaScript与代码隐藏和值插值分开.而不是动态构建JavaScript,那么方法就是拥有一个给定参数的JavaScript函数.

在第一阶段之后,我们最终得到了类似的东西(原谅部分翻译,这让我感到很伤心).注意使用闭包构建器模式;在实际代码中,我将进一步将其作为一个单独的模块.

function makeValidator(champId, opts) {
    return function (sender, args) {
        // Now this is when it gets harry..
        //
        // Use $get (and $find) inside ASP.NET, especially when
        // dealing with ASP.NET AJAX integration to find a control by ID.
        //
        // HOWEVER, the code uses what appears to be some DevExpress
        // controls and thus must be accessed.. differently, mainly either by
        //   1. `window[clientId]` or
        //   2. `ASPxClientControl.GetControlCollection().GetByName(id);`
        // This is just one of those icky things to deal with; I've shown usage
        // of the former and it may need to be applied to the other controls as well.
        //
        var reasonControl = window[opts.reasonId];        // DX control
        var dynamicControl = $get(opts.dynamicControlId); // normal ASP.NET/DOM
        var errorImage = window[opts.errorImageId];       // DX control
        if(reasonControl.GetText() != '' || dynamicControl.style.display == "none") {
            dynamicControl.className='';
            errorImage.SetClientVisible(false);
            args.IsValid = true;
        }
        // etc.
    }
}

应该清楚JavaScript代码与任何字符串插值是分开的.这是一个正常的函数,当使用某些参数(由API定义)调用时,具有某种行为.虽然有不同的方法来“加载/注入”这个JavaScript(当UpdatePanels和嵌套/复杂的层次结构发挥作用时这很重要),让我们假装它当前放在< script>内.在页面的标记中.

现在,让我们将验证器连接到控件 – 这完全是虚构的,但它显示了数据绑定的用法,并在代码隐藏中实际创建了JavaScript“调用”,我们将在一秒钟内看到原因. (正确使用数据绑定实际上很重要,因为它会延迟调用CreateValidator函数,直到分配了控件的ClientID为止.)

<!-- Use of the DataBind Container/Eval may be useful, but ignoring that.. --!>
<control:BlahBlah Id="ImaControl"
                  OnClientValidate="<%# CreateValidator(ImaControl) %>"/>

然后回到代码隐藏:

protected string CreateValidator(Control c) {
    var champId = c.ClientID; // example, not necessarily true

    // Then setup other values to supply to the function. While JSON is not
    // *exactly* like a JS object literal it is close enough so we Just Don't Care.
    // I prefer Json.NET from Newtonsoft, but the standard support is just fine.
    // (The champId could also be serialized here, but I chose to show passing
    //  two arguments, one NOT escaped; we assume champId doesn't contain \s or 's.)
    var opts = new JavaScriptSerializer().Serialize(new {
        reasonId = reasonControl.ClientID,
        dynamicControlId = dynamicControl.ClientID,
        errorImageId = Error9.ClientId
    });

    // The use of parenthesis and actual JavaScript returned depends on if the
    // client-side validation property takes JavaScript to execute (common) or if
    // it takes a function to execute later, as found in DevExpress/some libraries.
    // (Remember from above that makeValidator returns a new function.)

    // For DX/DevExpress:
    return string.Format("makeValidator('{0}', {1})", champId, opts);

    // Normal ASP.NET might look like this:
    return string.Format("return makeValidator('{0}', {1}).apply(this, arguments)",
                    champId, opts);
}

这就是它的要点,包括错误.但是,这种方法有很多种变化(包括ASP.NET AJAX ScriptControl魔术)和需要考虑的微妙因素;要记住和争取的重点是:

分离JavaScript代码并使用API​​来传达值.

标签:javascript,asp-net,webforms,code-behind,c-2
来源: https://codeday.me/bug/20190825/1713689.html