Trying to pass value (abc) from code-behind to JavaScript but the page fails and doesn't load. Is there something wrong with the syntax? I've noticed that normally the <%...%> is highlighted yellow but this is not the case in my code.
<script src="../Scripts/jqModal.min.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() { });
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = "<%=Variable_codebehind %>";
}
});
</script>
Code Behind On_Load event:
protected override void OnLoad(EventArgs e)
{
Variable_codebehind = "hello world";
}
Error from logfile:
Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
first bind the value to a hidden control
then get the value from the hidden control
<script src="../Scripts/jqModal.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = <%=Variable_codebehind %>;
}
});
});
</script>
Code Behind On_Load event:
protected override void OnLoad(EventArgs e)
{
Variable_codebehind = HttpUtility.JavaScriptStringEncode("hello world", true);
}
You can use Page.RegisterStartupScript and pass some variables from Code-Behind. Place the script in a .js file and call it on OnLoad method from the code-behind:
OnLoad CodeBehind:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", String.Format("MyScript({0});", codeBehindVar));
MyScript.js
function MyScript(myVar)
{
var self = this;
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = self.myVar;
}
}
Related
Hello i am failing to pass the value from dropdownlist in the parent aspx form to textbox in the child aspx form
Parent javascript
: The First script is to open the popup window
<script type="text/javascript">
var popup;
function NewCustOpn() {
popup = window.open("NewCustomer.aspx","Popup",toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=0,width=520,height=350,left = 250,top = 50");
}
</script>
This is the second script on the parent page to get the value of the dropdownlist
<script type = "text/javascript">
function parentFunc()
{
return document.getElementById ("<%=DropDownList1.ClientID%>").value;
}
</script>
The child page javascript:
<script type = "text/javascript">
window.onload = function ()
{
if(window.opener != null && !window.opener.closed)
{
var val = window.opener.parentFunc();
var textbox = document.getElementById("<%=TextBox1.ClientID%>");
textbox.Value = val;
}
}
</script>
When the popup opens TextBox1 is empty.
Your problem is simple. Just replace the below line from your child page's js function
textbox.Value = val;
to
textbox.value = val; // lowercase "v"
or justdo a direct assignment like this
document.getElementById("<%=TextBox1.ClientID%>").value = val;
Or another possible solution would be to directly pass the required value from the parent page as a querystring value and you don't need the js function in the popup page. The querystring value you can access it in child pages's page load event and assign it directly to the textbox.
Your Parent js
function NewCustOpn() {
var ddlvalue = document.getElementById("<%=DropDownList1.ClientID%>").value;
var popup = window.open("Popup.aspx?dropdownval=" + ddlvalue, "Popup", "toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=0,width=520,height=350,left = 250,top = 50");
}
And from you child page's code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["dropdownval"])) {
TextBox1.Text = Request.QueryString["dropdownval"];
}
}
I would like to show the modal window (executed in the JavaScript function below) on page load:
<script type="text/javascript">
$(function () {
$('.popup-wrapper').modalPopLite({
openButton: '.clicker',
closeButton: '#close-btn',
isModal: true
});
});
</script>
<asp:HyperLink ID="clic" Text="ck" runat="server" CssClass="clicker" NavigateUrl="#">
</asp:HyperLink>
<asp:Panel ID="cli" runat="server" CssClass="popup-wrapper" Width="500" Height="500" >
Close
</asp:Panel>
How do I do this in asp.net?
If you want it to show up on every page load, you can use JQuery .ready() function on the document object, which will execute this script when the DOM fully loads. Otherwise, what might be happening is you're executing the function before $('.popup-wrapper').modalPopLite() or whatever is initialized and getting a JavaScript error.
So you'd do this instead:
$(document).ready(function () {
$('.popup-wrapper').modalPopLite({
openButton: '.clicker',
closeButton: '#close-btn',
isModal: true
});
});
Now, if you want to only display this on the first page load, and not on any further postbacks, you'll need to tap into C# codebehind:
public partial class SomePage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// The # character denotes a string literal; just makes it easy to
// use multiple lines in this case and keep the inline javascript
// code looking nicely formatted within C#
ClientScript.RegisterStartupScript(this.GetType(), "PopModal", #"
$(document).ready(function () {
$('.popup-wrapper').modalPopLite({
openButton: '.clicker',
closeButton: '#close-btn',
isModal: true
});
});"
);
}
}
}
I want to close the RadWindow and refresh the parent : how to do this server side :
I have the following case:
Two pages say :
parent.aspx :
<telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableViewState ="false">
</telerik:RadWindowManager>
and parent.cs
protected void OpenNewWindow(string url, int width, int height,int mode)
{
RadWindow newWindow = new RadWindow();
newWindow.NavigateUrl = url;
newWindow.VisibleOnPageLoad = true;
newWindow.KeepInScreenBounds = true;
if (width > 0)
{
newWindow.Width = width;
}
if (height > 0)
{
newWindow.Height = height;
}
newWindow.VisibleStatusbar = false;
if (mode == 0)
{
newWindow.DestroyOnClose = true;
newWindow.InitialBehaviors = WindowBehaviors.Maximize;
}
RadWindowManager1.Windows.Add(newWindow);
}
i call this method in the rowcommand of some gridview on my parentpage :
like this :
OpenNewWindow("child.aspx", 0, 0,0);
Now i want on the server side click event of some button on the child page to close the rad window and refresh the parent one how to do this ??
As you said, you want to close from code behind. So you can render Page.ClientScript.RegisterClientScriptBlock(GetType(), "CloseScript", "refreshParentPage()", true); from code behind to refresh the parent.
Just add the following code and script in Child Page. No code is needed in parent page.
<script>
function getRadWindow() {
var oWindow = null;
if (window.radWindow)
oWindow = window.radWindow;
else if (window.frameElement.radWindow)
oWindow = window.frameElement.radWindow;
return oWindow;
}
// Reload parent page
function refreshParentPage() {
getRadWindow().BrowserWindow.location.reload();
}
</script>
<asp:Button runat="server" Text="Close" ID="CloseButton"
OnClick="CloseButton_Click"/>
protected void CloseButton_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(GetType(),
"CloseScript", "refreshParentPage()", true);
}
Update:
// Redirect page page to url
function redirectParentPage(url) {
getRadWindow().BrowserWindow.document.location.href = url;
}
// Code behind
Page.ClientScript.RegisterClientScriptBlock(GetType(),
"CloseScript", "redirectParentPage('Parent.aspx')", true);
You should use the getRadWindow().close() method and the OnClientClose event.
On Child.aspx:
<script type="text/javascript">
function getRadWindow() {
var oWindow = null;
if (window.radWindow)
oWindow = window.radWindow;
else if (window.frameElement.radWindow)
oWindow = window.frameElement.radWindow;
return oWindow;
}
function clientClose(arg) {
getRadWindow().close(arg);
}
</script>
In Child.cs:
protected void btn_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Page, typeof(Page), "closeScript", "clientClose('');", true);
}
When creating your RadWindow in Parent.cs, add the OnClientClose event: newWindow.OnClientClose = "OnChildWindowClosed";.
And on Parent.aspx:
<script type="text/javascript">
function OnChildWindowClosed(sender, eventArgs) {
document.location.reload(); // there may be a cleaner way to do the refresh
}
</script>
Simple way to force closing rad window, just put it inside update panel like that :
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" RenderMode="Block">
<ContentTemplate>
<telerik:RadWindow ID="RadWindow1" runat="server">
<ContentTemplate>
</ContentTemplate>
</telerik:RadWindow>
</ContentTemplate>
</asp:UpdatePanel>
Important: you have to apply this properties to the update panel :
UpdateMode="Conditional" RenderMode="Block"
then inside the button you want to execute the close command perform :
UpdatePanel1.update()
this command will close radwindow and no refresh to your Webpage and no need to javascript, I tried it.
Using jQuery I'm trying to get the id of control, which I clicked (radiobutton). I read this question and tried almost everything from there:
alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);
But I'm always getting: Undefined
I just don't understand what I'm doing wrong.
UPDATED:
Radiobuttons is generated dynamically in code behind by C#:
controlToReturn = new RadioButton
{
ID = controlId
};
((RadioButton)controlToReturn).Text = text;
((RadioButton)controlToReturn).Checked = Convert.ToBoolean(Convert.ToInt32(value));
((RadioButton)controlToReturn).GroupName = groupName;
((RadioButton)controlToReturn).CssClass = cssClass;
((RadioButton)controlToReturn).Attributes.Add("runat", "server");
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show();");
and function in ASPX:
<script type="text/javascript" language="javascript">
function Show() {
if ($(this).cheked = true) {
console.log(this);
alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);
}
}
</script>
I know radiobutton has id, I checked generated HTML.
Your problem is this has no context within your function and is in fact the window itself.
You would need to modify both the output html to provide context as an argument:
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");
and change the function Show:
function Show(el) {
/* for jQuery use $(el) */
if(el.checked) {
alert(el.id);
}
}
C#:
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");
JavaScript:
function Show(radio) {
if (radio.checked) {
alert(radio.id);
}
}
To attach a click-listener and alert the ID, your code would look something like this:
$(function () {
$("input[type='radio']").on("click", function () {
alert(this.id);
});
});
A working demo: http://jsfiddle.net/SSBnV/1/
I am using jquery Carosellite and Cycle to display images like frames. How to pass values to the properties like speed, visible ect from codebehind(c#).
Ex html code:
<script type="text/javascript" language="javascript">
$(function() {
$(".anyClass").jCarouselLite({
btnNext: ".next",
btnPrev: ".prev",
visible: 1,
scroll: 1,
speed: 1000
});
});
</script>
Geetha.
If you don't like mixing ASP.NET code your mark-up you could also do this:
markup:
<asp:HiddenField runat="server" id="hfVisible" Value="true" />
<asp:HiddenField runat="server" id="hfSpeed" Value="1000" />
javascript:
$(function() {
$(".anyClass").jCarouselLite({
btnNext: ".next",
btnPrev: ".prev",
visible: $('#hfVisible').val(),
scroll: 1,
speed: $('#hfSpeed').val();
});
});
code behind:
protected override void OnLoad(EventArgs e) {
hfVisible.Value = true;
hfSpeed.Value = 1000;
}
Note: if the HiddenFields are on a UserControl do not use the id to reference the elements, use class instead, or another attributes; or to avoid this: use the RegisterHiddenField:
ClientScriptManager cs = Page.ClientScript;
// Register the hidden field with the Page class.
cs.RegisterHiddenField('hfVisible', "false");
cs.RegisterHiddenField('hfSpeed', "1000");
In this way, you don't need to declare HiddenFields in the markup.
If the properties are in the codebehind, you can stick them in the page for a quick solution:
$(function() {
$(".anyClass").jCarouselLite({
btnNext: ".next",
btnPrev: ".prev",
visible: <%=Visible %>,
scroll: 1,
speed: <%=Speed %>
});
});
In the page:
protected int Visible { get; set; }
protected int Speed { get; set; }
protected override void OnLoad(EventArgs e) {
Visible = 1;
Speed = 1000;
}