最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to include javascript file in the cs code behind in asp.net - Stack Overflow

programmeradmin2浏览0评论

In default.aspx I have:

 <form id="form1" runat="server">
    <div>
    <asp:Button ID="clikme" runat="server" Text="click me" />    
    </div>
    </form>

In default.aspx I have:

clikme.Attributes.Add("OnClick", "javaScript: return myfunction();");

And in JScript1.js I have

function myFunction() {
    alert('this is my function');
    return false;
}

The above code does not work it shows 'Microsoft JScript runtime error: Object expected'. I can't figure out how to find a solution.

In default.aspx I have:

 <form id="form1" runat="server">
    <div>
    <asp:Button ID="clikme" runat="server" Text="click me" />    
    </div>
    </form>

In default.aspx I have:

clikme.Attributes.Add("OnClick", "javaScript: return myfunction();");

And in JScript1.js I have

function myFunction() {
    alert('this is my function');
    return false;
}

The above code does not work it shows 'Microsoft JScript runtime error: Object expected'. I can't figure out how to find a solution.

Share Improve this question edited Mar 28, 2018 at 9:51 MSeifert 153k41 gold badges350 silver badges367 bronze badges asked Sep 2, 2013 at 6:49 user2380844user2380844 3075 gold badges16 silver badges30 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 1

You are call function with wrong name myfunction() should be myFunction() as javascript is case sensitive. Also make sure you include the JScript1.js in the current aspx file. You can read this MSDN artile to learn how to include js file.

clikme.Attributes.Add("OnClick", "javaScript: return myFunction();");

To include js file

<script type="text/javascript" src="yourDirectorIfAny/JScript1.js" ></script>

try this add

script type='text/javascript' language="javascript" to your js portion and place your function inside it..

try

clikme.Attributes.Add("OnClientClick", "javaScript: return myFunction();");

The best way is to give reference of javascript file on Aspx page itself as suggested by Adil. If you want to register some javascript methods in code behind then you can have a look at this example.

http://msdn.microsoft./en-us/library/system.web.ui.page.registerclientscriptblock.aspx

Something like below will helpfull.. 

string script = "myFunction();";
AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert", script, true);             

JScript is CASE SENSITIVE language.

clikme.Attributes.Add("OnClick", "javaScript: return myfunction();");
function myFunction() {
...
}

Check above lines. myFunction function must be equal.

发布评论

评论列表(0)

  1. 暂无评论