calling a javascript function from the inlinecode aspx
I have the working code pasted below which has a function called FormatStatus() as part of inline code and the actual definition is in the code behind (C#)开发者_开发百科. My question is if I move the function (FormatStatus()) into an external javascript file how can i call it from the inline code.
<asp:Label ID="lblSts" runat="server" Text= '<%# FormatStatus(Eval("StsId").ToString()) %>' >
</asp:Label>
My code behind :
protected string FormatStatus(string Id)
{
string formatText = string.Empty;
switch (int.Parse(Id))
{
case 0:
formatText = "New";
break;
case 1:
formatText = "Old";
break;
.....
}
return formatText;
}
JavaScript function can be called by any event only. If you want to run js function as initial method you can use window.onload. So, you can create global javascript array in your page and fill it with id values from c# behind code and call formatStatus on window.load:
if (!Page.ClientScript.IsStartupScriptRegistered("preloadArray" + this.ClientID))
{
string script = "<script type='text/javascript'> ";
for (int i = 0; i < ...; i++)
{
script += "arr.push("+i.ToString()+");";
}
script += "formatStatus('" + gvAdminActiveAsgnments.ClientID + "');";
script += "</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(),
"preloadArray" + this.ClientID, script);
}
(you can use Page_Load or ItemDataBound handler)
Then you should write function, which take one argument with id of grid:
function formatStatus(id){
var table = document.getElementById(id);
var rows = table.getElementsByTag('TR');
for(var i=0; i<rows.length;i++){
//puts into label from table row result for arr[i]
}
}
It will be invoked on page load for your table, which will rendered from asp:GridView. You can bind formatStatus to any event, e.g. click by some button. So, it will change labels.
You can try to do it this way, just make sure to include the external js file on top of the document.
<asp:Label ID="lblSts" runat="server">
<script type="text/javascript">
document.write(FormatStatus('<%# Eval("StsId").ToString() %>');
</script>
</asp:Label>
精彩评论