c# - 在 C# CodeBehind 中为 javascript 变量赋值

标签 c# javascript asp.net

如何从代码隐藏 (C#) 为 javasctipt 变量赋值?

<script type="text/javascript">
String.prototype.trim = function () { return this.replace(/^\s+|\s+$/, ''); };
function ConstantByCode(_Obj, _Div) {
    var pl = new SOAPClientParameters();
    _Obj.value = _Obj.value.trim();
    pl.add("Code", _Obj.value);
    pl.add("Group", _Obj.Grp);
    alert(_Obj.Grp);
    var _Value = SOAPClient.invoke("ConstantWS.asmx", "GetConstantByCode", pl, false, CallBackEvent);
    if (_Value == null || _Obj.value == "" || _Obj.value == null || IsNumeric(_Obj.value) == false) {
        _Obj.value = "";
        _Div.innerHTML = "";
    }
    else {
        _Div.innerHTML = _Value;
    }
}


function CallBackEvent(r) {

}
function IsNumeric(input) {
    return (input - 0) == input && input.length > 0;
}

代码背后

 txtCode.Attributes.Add("Grp", Me.ConstValue)
    txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")
    txtCode.Attributes.Add("onkeyup", "ConstantByCode(this," & DivTitle.ClientID & ");")

_obj.Grp 现在有值了。 警报说:未定义

最佳答案

我看到您想检索作为自定义属性的 Grp 的值。您需要使用 getAttribute 函数 - 因此您需要使用 _Obj.getAttribute("Grp") 而不是 _Obj.Grp

另外,我看到您没有将客户端 ID 括在来自 ode-behind 的引号中。所以不是

txtCode.Attributes.Add("onchange", "ConstantByCode(this," & DivTitle.ClientID & ");")

你要说

txtCode.Attributes.Add("onchange", "ConstantByCode(this,'" & DivTitle.ClientID & "');")

请注意客户端 ID 周围的单引号 (')。

此外,ConstantByCode js 函数似乎正在获取 div 元素。因此,您需要向其中添加一行以将客户端 ID 转换为实际的 DOM。即

function ConstantByCode(_Obj, _Div) {
   _Div = document.getElementById(_Div);
   .... // rest of the code

关于c# - 在 C# CodeBehind 中为 javascript 变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3655766/

相关文章:

c# - 在 asp 中使用文字而不是 html 的原因和好处

c# - 在异步方法结束时,我应该返回还是等待?

javascript - 下一个按钮用js选择下拉菜单的下一个选项

javascript - 可以在 ReactJS 中的 anchor 标记上调用 onClick 吗

c# - 嵌套在 GridView 中的 Databound 转发器不会更新

c# - CompositionTarget.Rendering 未调用?

c# - 在 Azure Web 应用程序上运行 Selenium

javascript - 通过 JavaScript 获取我的网站中当前 Windows 用户的用户 ID

c# - 在 ASP.NET (MVC) 中从 CSV/Excel 导入期间标准化数据的推荐方法是什么?

asp.net - 填充下拉列表框时为其提供工具提示