Sharepoint Custom WebPart启动脚本

时间:2010-07-26 20:09:10

标签: javascript sharepoint web-parts registerstartupscript

好的,我已经遇到了一个我试图解决两天的独特问题。

我有System.Web.UI.WebControls.WebParts.WebPart控件我正在构建一个自定义的Sharepoint View。除了一个小问题外,我想做的几乎所有事情都在起作用。我需要使用Javascript格式化日期和货币字段。客户希望DateTime字段为mm / dd / yyyy,货币在适当的位置有$和逗号。

这在常规aspx页面上的javascript中很容易。我刚写了函数和页面加载

protected void Page_Load(object sender, EventArgs e)  
{  
    if (!IsPostBack)  
    {  
        GridFieldDAO dao = new GridFieldDAO();  
        myGrid.DataSource = dao.getItems();  
        myGrid.DataBind();  
    }  
    GetBuildFormattingScript();  
}  

private void GetBuildFormattingScript()  
{  
    string script = "<script type=\"text/javascript\">";  
    script += " FormatByRows(\"" + myGrid.ClientID + "\",2);";  
    script += " FormatByRowsDate(\"" + myGrid.ClientID + "\",1);";  
    script += "</script>";  
    if(!ClientScript.IsClientScriptBlockRegistered("DoFormatting"))  
    ClientScript.RegisterStartupScript(typeof(string), "DoFormatting", script);  

    string script2 = "   <script type=\"text/javascript\">"+   
        "var prm = Sys.WebForms.PageRequestManager.getInstance(); "+  
        "prm.add_beginRequest(BeginRequestHandler); "+  
        "prm.add_endRequest(EndRequestHandler); "+  
        "function BeginRequestHandler(sender, args)  "+  
        "{ }"+  
        "function EndRequestHandler(sender, args)  "+  
        "{ FormatByRows(\"" + myGrid.ClientID + "\",2); "+  
        " FormatByRowsDate(\""+myGrid.ClientID+"\",1);}</script> ";  

    if (!ClientScript.IsClientScriptBlockRegistered("DoUpdateFormatting"))  
        ClientScript.RegisterStartupScript(typeof(string), "DoUpdateFormatting", script2);  
}

我的问题是在WebPart的OnLoad上我想要更新的网格不存在......所以我必须向OnPreRender添加代码。

好吧,WebPArt加载并且Javascript不会触发......所以我点击刷新它就会触发。任何人都可以帮助我获取初始WebPart Load的代码吗?有没有人能够让服务器端脚本在SharePoint中以这种方式工作?

谢谢, Mike V

1 个答案:

答案 0 :(得分:4)

为此,您可以利用_spBodyOnLoadFunctionNames

string script = "<script type=\"text/javascript\">";   
script += " function FormatDataGridRows() {";
script += "    FormatByRows(\"" + myGrid.ClientID + "\",2);";   
script += "    FormatByRowsDate(\"" + myGrid.ClientID + "\",1);";   
script += " }";
script += " _spBodyOnLoadFunctionNames.push('FormatDataGridRows');";
script += "</script>";   

修改的 要进行测试,请将以下代码放在页面上的内容编辑器Web部件中:

<script type="text/javascript">
function SayHello() {
   alert('hello world!');
}
_spBodyOnLoadFunctionNames.push("SayHello");
</script>