Link javascript file dynamically in asp.net - asp.net

I want to link to a javascript file in header dynamically
<script src='<%=Global.RootPath%>js/jquery1.4.2.js' type="text/javascript"></script>
<script src='<%=Global.RootPath%>js/jquery.mousewheel-3.0.4.pack.js' type="text/javascript"></script>
but I got an error
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: The Controls collection
cannot be modified because the control contains code blocks (i.e. <%
... %>).
I want to add javascript file dynamically. Please explain why I am getting this error and is there any other method to do this?

Yes this is a common error when you try to render content like that on the header.
You can do alternative thinks like:
Place a literal control, and fully render your script line on code behind.
<asp:Literal runat="server" id="txtScripts" EnableViewState="false" />
and render the full line on code behind as
txtScripts.Text = string.Format(
"<script src='{0}js/jquery1.4.2.js' type=\"text/javascript\"></script>", Global.RootPath);
Or alternative you can create them totally dynamically and added to the header control list.

To include a javascript you can also include at the end of document itslef. If you want to specifically insert at the header then create a literal control and set its text to your script tags and add it to Page.Headers.

Related

“The Controls collection cannot be modified because the control contains code blocks”

While trying to insert controls in my page with the following block of code, i got this exception
The Controls collection cannot be modified because the control
contains code blocks
Literal lite=new Literal();
lite.Text = #"<div class='cookieLaw_slidesharey'><a id='cookieLaw_slideshare' href='#'><img src='/img/content/cookielaw_slideshare.jpg'/></a></div>";
Control control = this.FindControl("PlaceHolder");
control.Controls.AddAt(0,lite);
I tried to follow the advices written in this thread:
"The Controls collection cannot be modified because the control contains code blocks"
Which are basically:
replacing <%= %> with <%# %>
And adding
Page.Header.Databind() in the page load
But i get the following exception:
Object reference not set to an instance of an object.
Thank you for your help.
PS: i'm using .NET 3.5
Check if your "PlaceHolder" has a runat=server attribute. That should already help. You can address that control by it's id then instead of using FindControl.
The reason why your Page.Header.Databind() is not working is probably because you don't have a head section with the runat=server like in the example you copied from. They were adding controls in the header there which can be slightly different.

Sharepoint .aspx page

I have been told I will be let go at the end of the week if I can't figure this out by the end of the day. I need help in figuring out this issue. I am trying to create a .aspx page for a sharepoint site. This is the code I have...
<script runat="server">
Sub submit(Source As Object, e As EventArgs)
button1.Text="You clicked me!"
End Sub
</script>
<!DOCTYPE html>
<html>
<body>
<form runat="server">
<asp:Button id="button1" Text="Click me!" runat="server" OnClick="submit" />
</form>
</body>
</html>
I keep getting error messages every time I load the page. I ripped this code off the internet and when I load the page it says:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Code blocks are not allowed in this file.
Source Error:
Line 3: button1.Text="You clicked me!"
Line 4: End Sub
Line 5: </script>
Line 6:
Line 7: <!DOCTYPE html>
Please help me. Why am I getting this message?
SharePoint doesn't allow inline code in .aspx files by default. You'll need to change that setting in the web.config if you want to do this, but it's not recommended. See the link #Mark posted in the comments.
As an alternative, you can create a webpart, and add that to the page. See this article for more help on how to do this.
You can allow adding code inside sharepoint pages by adding below lines in the web.config file
<PageParserPaths>
<PageParserPath VirtualPath="/pages/test.aspx" CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
Where "/pages/test.aspx" is the path of your page , or you can add it as "/_catalogs/masterpage/*" for example to add all masterpages files.

ASP.NET MVC 2 client side validation not working for Html.ValidationMessage()?

I'm trying to get a very simple client side validation example to work in ASP.NET MVC 2. I'm using data annotations to set a required property "Surname". When I use the Html.ValidationMessageFor(x => x.Surname) the correct client side validation script is written to the page. But when I use Html.ValidationMessage("Surname") the client side validation is not rendered out until after the page has been posted. Client side validation only starts working after a form post! I can see that the script is updated in the page after a form post. There appears to be a bug in Html.ValidationMessage()?
Make sure you are referencing the correct scripts in your master page head.
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftMvcValidation.js") %>" type="text/javascript"></script>
also look at your view to make sure the client validation call is above your form
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
...
<% } %>
and of course your validation message to show the problem.
<span class="editor-label"><%= Html.ValidationMessageFor(u => u.Name)%></span>
That is really all you need. I believe the required attribute will only start its check if you enter text in the field then remove the text and tab out of the field, so try that to see if you get the validation. Others will validate when the attribute needs to. For example the [StringLength(50)] will show an error message when you exceed 50 characters.
i've not tried but the metadata are stored on the proprerty so only the ValidationMessageFor has the ability to check the prop (via static reflection).
The other helper use a string key to access a modelstate dictionary without any reference to the property (and no validation metadata info), so i dot't think the Html.ValidationMessage(string key) has the ability to inject validation script client-side.
As far as I know the validation requires an attempt to validate even if it's client side.
You could try on the GET view creating a new instance of your model, then use TryValidateModel() before sending it to the view. This should cause the validation logic to run and thus to populate the clientside validation, this will result in all required fields showing their error version but depending how you choose to style them this doesn't have to be a big issue.

Usercontrol access Javascript from a Content's Page's Master Page

Hello all I have a problem. I have a masterpage that all of my Content pages inherit from. Within this masterpage I have a script tag pointing to the Javascript file folder ~/Scripts/validation.js
On my content pages I use different usercontrols that require the use of many of the functions within the validation.js file however if I dont put the <script> tag and the Javascript functions within a contentholder on the contentpage the usercontrols do not see these functions and I get errors like OnNameValidation is not defined.
Of course I can copy the Javascript code into all of the pages but that's 30+ pages and a maintenance nightmare if I find a bug in one of the Javascript functions.
So the question (if you haven't already figured out from my long dissertation) is how can I declare the script tag with the path to the validation.js file so that contentpages and their usercontrols etc. can access the functions/code.
What you are trying to do should work, so I suspect that the path to your javascript file is wrong (without seeing your html code I can only assume). Keep in mind that you can only reference the javascript file like this: "~/Scripts/validation.js" if you have the link in a HEAD runat="server" tag. Without the runat="server" it won't find the file. You would have to do something like "../scripts/validation.js"
As a test I would try to call your javascript function in the masterpage, so you can rule out a bad file reference.
I picked up this tip from ScottGu here.
Add this to you user control which enables Intellisense in user controls but always evaluates false:
<% if (false) { %>
<script src="/Scripts/validation.js" type="text/javascript"></script>
<% } %>
I am currently doing this in my site by going to the Source code on the master page and putting the following in the head and outside of the ContentPlaceHolder.
<head>
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
<script src="CP.js" type="text/javascript"></script>
</head>
The path you are assigning for your js file is probably not matching in all the pages.
script src="../JavaScript/Scriptaculous/scriptaculous.js"
It should have something like above this if you have separate folder for Scripts, MasterPages, Pages & Controls.

How do I make the children appear in a custom webcontrol for ASP.NET?

For example, I have a custom control called SampleControl. To simplify things for this question, pretend I'm making just a Panel Control clone from scratch.
<CC:SampleControl ID="Sample1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Hi"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button1"></asp:Label>
</CC:SampleControl>
To Output:
<div id="Sample1">
<span id=Label1>Hi</span>
etc.....
</div>
Where the Code is:
public class SampleControl: WebControl
{
.....Render Stuff Goes Here.....
}
The ASP controls in the middle aren't being registered by ASP.NET. When I did a Reflector on the Panel control, I couldn't find out how they got the middle controls to render. It doesn't look like they are using a Templated Control.
When I do it, I get this error:
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Any Ideas?
First, [ParseChildren(false)] attributes lets parser know that you want your control to treat nested content as child controls.
Then make sure that somewhere in Render the RenderChildren method is called. It's the default implementation of System.Web.UI.Control.Render(), so you can do base.Render(writer) in your overriden Render method.

Resources