Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

javascript - C#.NET从HTML的内容页面调用母版页方法(C# .NET Call Master Page Method from Content Page in HTML)

In my Site.Master Page (SiteMaster) I have the following code:(在我的Site.Master页(SiteMaster)中,我具有以下代码:)

public string RandomString() { Random random = new Random(); return new string(Enumerable.Repeat("ABCEFG", 10) .Select(s => s[random.Next(s.Length)]).ToArray()); } this should give me a random string.(这应该给我一个随机的字符串。) Now in my ContentPage.aspx I want to call this function the same time as Im trying to import a Js File so first I imported the MasterType on top of the page like this:(现在在我的ContentPage.aspx中,我想在我尝试导入Js文件的同时调用此函数,因此首先我将MasterType导入到页面顶部,如下所示:) <%@ MasterType VirtualPath="~/Site.Master" %> and then import my js script like this:(然后像这样导入我的js脚本:) <script type="text/javascript" src="/Scripts/Custom/myJSFILE.js?rndstr=<%= Master.RandomString(); %>"></script> But if I try to run it I get the following error:(但是,如果我尝试运行它,则会收到以下错误:) Error compiling a resource needed to handle this request.(编译处理该请求所需的资源时出错。) Review the following specific error details and change the source code accordingly.(查看以下特定的错误详细信息,并相应地更改源代码。) Compiler error message: CS1026:) expected(编译器错误消息:CS1026 :)预期) But somehow If I do the same in the MasterSite.aspx file like this:(但是以某种方式,如果我在MasterSite.aspx文件中这样做,如下所示:) <script type="text/javascript" src="/Scripts/Custom/myJSFILE.js?rndstr=<%# RandomString() %>"></script> It works like a charm.(它像一种魅力。) So how can I call the same function in my Content pages aswell?(那么,如何在“内容”页面中调用相同的函数?)   ask by Lukas R. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot access the Master page directly, you need to create a property of it, and use that to access the methods.(您不能直接访问母版页,需要创建它的属性,然后使用该属性来访问方法。)

Site1 is the class name of the Master page ( public partial class Site1 : System.Web.UI.MasterPage )(Site1是母版页的类名称( public partial class Site1 : System.Web.UI.MasterPage )) public Site1 MyMaster; protected void Page_Load(object sender, EventArgs e) { MyMaster = (Site1)Page.Master; } And then you have access in the aspx(然后您就可以访问aspx) <%= MyMaster.RandomString() %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...