RegisterStartupScript only runs the first time. ASP.NET C# JavaScript - javascript

I have an .aspx page with the following code
<asp:Panel runat="server" ID="ImagePanel">
<asp:UpdatePanel runat="server" ID="ImageUpdatePanel" UpdateMode="Conditional"><ContentTemplate>
<img id="photo" src="/Icons/Factory Layout.png" style="display: none;"/>
<script type="text/javascript">
function ResetImage(typeOfImage) {
var factoryImage = $("#photo");
if (typeOfImage === 1) {
factoryImage.attr("src",document.getElementById('<%= FactoryImageFileNameHF.ClientID %>').value);
}
else if (typeOfImage === 2) {
factoryImage.attr("src",document.getElementById('<%= IncidentFactoryImageFileNameHF.ClientID %>').value);
}
It is the ResetImage javascript function that I am trying to run with the following code in the code behind.
if (typeOfMap == 1)
{
FactoryImageFileNameHF.Value = fileNameOfFactoryImage.FileFullPath();
ClientScript.RegisterStartupScript(Page.GetType(), "test" + ScriptKeyHF.Value, "ResetImage(1);", true);
ScriptKeyHF.Value = (ScriptKeyHF.Value.ToInt() + 1).ToString();
}
else if (typeOfMap == 2)
{
IncidentFactoryImageFileNameHF.Value = fileNameOfFactoryImage.FileFullPath();
ClientScript.RegisterStartupScript(Page.GetType(), "test" + ScriptKeyHF.Value, "ResetImage(2);", true);
ScriptKeyHF.Value = (ScriptKeyHF.Value.ToInt() + 1).ToString();
}
The problem is that the ResetImage() method that I am calling in the RegisterStartUpScript only runs the first time on the browser. It doesn't run the second and third time of postbacks, etc.
I have tried the RegisterClientScriptBlock but it runs before the javascript code is there. Does anyone have any idea why the code only runs the first time.

The solution is that I was using a ClientScriptManager (ClientScript) instead of the a ScriptManager so I changed the line of code to
System.Web.UI.ScriptManager.RegisterStartupScript(this.Page,Page.GetType(), "test" + ScriptKeyHF.Value, "ResetImage(1);", true);
and it works.
I have the ScriptManager on a Master page and my code was on a child page

Related

Adding Hyperlinks to ValidationSummary using programatically added validators

I'm using the javascript from the answer in this question in a project of mine:
Adding Hyperlinks to ValidationSummary
It works really great. I've added it to the bottom of my masterpage (for some reason, even though it is inside $(document).ready, Page_Validators is null if i place it in the head section)
Anyway! I'm also adding some custom validators programatically on postback using this code:
public static CustomValidator ReturnErrorMessage(string message, string validationGroup, string controlToValidate = "")
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ErrorMessage = message;
control.ControlToValidate = controlToValidate;
return control;
}
However whenever I add a CustomValidator like that, in a button event, page_load or whatever, Page_Validators will be overridden and the errormessage will revert to the message without a anchor.
What gives? Am I doing something wrong or can someone explain what is happening?
I've tried debugging it and it does set the values correctly, but then it just reset afterwards.
I've tried for the heck of it and in $(document).ready set all validators as isvalid = false, and that gets overwritten too.
Im using asp.net 4.5 unobtrusive validation, but it does not make a difference if I turn it off.
Adding the javascript in code using Page.ClientScript.RegisterStartupScript at some point after the validator has been created does not work either.
If I don't add any validators in code everything works as expected.
I'm aware I can just add the anchor tags manually, but this is a lot of work to update existing validators instead of just tossing in a small script, so I'm hoping to get this to work.
You can use this code to test this:
using System;
using System.Web.UI.WebControls;
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + txtName.ClientID;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = "errorGroup";
control.ErrorMessage = "Error message";
control.ControlToValidate = txtName.ClientID;
Form.Controls.Add(control);
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:ValidationSummary ID="vsSummary" runat="server" ValidationGroup="errorGroup" ForeColor="Red" HeaderText="Error!" />
</div>
</form>
<script>
$(document).ready(function() {
var validators = Page_Validators; // returns collection of validators on page
$(validators).each(function() {
//get target control and current error validation message from each validator
//[0] is needed when using aspnet 4.5 unobtrusive validation
var validator = $(this)[0];
var errorMsg = validator.errormessage;
var targetControl = validator.controltovalidate;
//make link only if theres a control to target
if (targetControl) {
var errorMsgWithLink = "<a href='#" + targetControl + "' style='color: #FF3232;'> " + errorMsg + "</a>";
//update error message with anchor tag
validator.errormessage = errorMsgWithLink;
}
});
});
</script>
</body>
</html>
If you want you can try implementing your own 'CustomValidationSummary' control by following the same design pattern as mentioned at Reference Source by Microsoft, and modify the render method to include anchor tag to wrap error text, before it is passed into the writer method at line number 462.
I ended up using a extension method, adding the anchor tag in the method
public static void AddValidator(this Page p, string message, string validationGroup, string controlToValidate = "", bool addAnchorTags = true)
{
CustomValidator control = new CustomValidator();
control.ID = "cv" + controlToValidate;
control.IsValid = false;
control.Text = " ";
control.ValidationGroup = validationGroup;
control.ControlToValidate = controlToValidate;
if (addAnchorTags && !string.IsNullOrEmpty(controlToValidate))
{
control.ErrorMessage = "<a href='#" + controlToValidate + "' style='color: #FF3232;'> " + message + "</a>";
}
else
{
control.ErrorMessage = message;
}
p.Validators.Add(control);
}

Can't call alert from Server Side

In Web Forms project i need to open alert.
I try to do it like this
var script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "SignOffAlert"))
{
script.RegisterClientScriptBlock(this.GetType(), "text", "SignOffAlert");
}
and add js-function on view
function SignOffAlert() {
alert('The form cannot be submitted!');
}
On Button click alert is absent
Update :
This code works for me
var script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "signOffAlert"))
{
script.RegisterClientScriptBlock(this.GetType(), "signOffAlert", "alert('The form cannot be submitted!');", true);
}
try this,
in the Page_Load write this:
string myscript = " <script> function SignOffAlert() { alert('The form cannot be submitted!');}</script>";
if (! Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "SignOffAlert"))
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "text", myscript);
}
and in then Form
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="SignOffAlert()" />
You need to register the full script, i believe
have you seen the example here? http://msdn.microsoft.com/it-it/library/bahh2fef%28v=vs.110%29.aspx

Javascript method call from code behind

I visited Calling java script from codebehind and other questions marked as duplicate by some users. But specific to my problem none of them are helpful.
I have an already built CMS and I need to change one of the module which was built using a user control. I cannot hereby add runat="server"attribute to the form and head tags.
I am having a
<asp:GridView ID="gdvResxKeyValue" runat="server" Width="100%"AutoGenerateColumns="False">`</asp:GridView>`
and
<asp:TreeView ID="tvList" ShowLines="True" runat="server" ImageSet="Msdn" OnSelectedNodeChanged="tvList_SelectedNodeChanged">
<SelectedNodeStyle CssClass="sfSelectednode" />
</asp:TreeView>
gdvResxKeyValue is bind while selection of nodes is made in treeview ie.
protected void tvList_SelectedNodeChanged(object sender, EventArgs e)
{
gdvResxKeyValue.DataSource = lstResDef;
gdvResxKeyValue.DataBind();
this.Page.ClientScript.RegisterStartupScript(this.GetType(),LocalizationGlobalVariable5", string.Format("edition();"), true);
}
At last column of gdvResxKeyValue I have an image as
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imgEditResxValue" CssClass="sfEdit" runat="server" ImageUrl="~/Administrator/Templates/Default/images/imgedit.png" />
</ItemTemplate>
</asp:TemplateField>
and I need a image click handler using javascript using minified version of jquery-1.9.1.js. so have written code as..
<script type="text/javascript">
//<![CDATA[
$.Localization = {
TextAreaID: 0,
FilePath: "",
ID: 0,
GridID: '<%=gdvResxKeyValue.ClientID%>'
};
function edition() {
$('#'+ $.Localization.GridID).on('click', 'img[class="sfEdit"]', function () {
var index = $(this).attr("alt");
$.Localization.ID = index;
var data = $('#' + $.Localization.GridID + ' textarea[title="' + index + '"]').val();
$('#txtResxValueEditor').val(data);
ShowPopUp("editorDiv");
});
}
</script>
But it is not working.
Try to put your grid to div wrapper:
<div id="myDiv">
....<asp:GridView ID="gdvResxKeyValue"....
</div>
and JavaScript:
$('#myDiv .sfEdit').click(function(){
alert('called');
});
EDIT: just noticed you call the startup script registration on every postback (the Change event of your treeview). It's not needed. Simply include your JavaScript file, something like:
$(document).ready(function(){
$('#myDiv .sfEdit').click(function(){
var imgId = $(this).attr('id');
alert('called ' + imgId);
});
});
and keep the gridview in div wrapper as described above.
Rather calling javascript method on clicking the image. On the ready of document I have written following code and finally got my problem solved.
$(document).on('click', "#" + $.Localization.GridID + ' img.sfEdit', function (e) {
var index = $(this).attr("alt");
$.Localization.ID = index;
var data = $('#' + $.Localization.GridID + ' textarea[title="' + index + '"]').val();
$('#txtResxValueEditor').val(data);
ShowPopUp("editorDiv");
e.preventDefault();
});

Get Global Resource File from separate javascript file

I would like to set button text with different languages based on Culture. I have all my Javascript code in separate file. This file is imported in ToolkitScriptManager in Master Page. I have created JSString.resx global resource file. I have written code:
function showSessionTime() {
$(".sessionTime").val('<%= GetGlobalResourceObject("JSString", "SessionTime").ToString() %>' + " " + convertTime(minutes) + ":" + convertTime(seconds)); seconds = seconds - 1;
}
The function is then called in $(document).ready(function ()...
The button in Master Page:
<asp:Button ID="Button2" runat="server" class="ui-state-default ui-corner-all sessionTime"
UseSubmitBehavior="False" OnClientClick="javascript:return false;"
meta:resourcekey="Button2Resource1"></asp:Button>
I know that <%= GetGlobalResourceObject("JSString", "SessionTime").ToString() %> doesn't work in separate js files. How to workaround this as simple and as quick as possible?
I check value like this:
if ($("#ctl00_ddlLanguage").val() == 'pl-PL') {
expiredMessage = 'Twoja sesja wygasła. Zostałeś wylogowany.';
}
else {
expiredMessage = 'You session has ended. You have been logged out.';
}
Is there any risk of using #ctl00_ddlLanguage??

How can I write javascript functions in content page html and how I call that function

I write two javascript functions in content page. Then I take a html textbox and on the onkeypress event I try to call those two functions, but I am running that application and I didn't find any output to help me.
Here I am trying to count number of characters in textbox on keypress event. If I write a javascript function in simple page then it runs successfully but it doesn't run in content page help me.
Here is the code
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile ="~/Site1.Master" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<asp:Content ID="Content1" runat="server"
contentplaceholderid="ContentPlaceHolder1">
<script language ="javascript" type = "text/javascript">
maxL=0;
var bName = navigator.appName;
function taCount(taObj,Cnt,totmsg)
{
objCnt=createObject(Cnt);
objtotmsg = createObject(totmsg);
objVal=taObj.value;
if (objCnt)
{
if(bName == "Netscape")
{
//objCnt.textContent = maxL-objVal.length;}
var totalchar = parseInt((objVal.length - 1) / 160);
objCnt.textContent = maxL + objVal.length;
objtotmsg.textContent = totalchar + 1;
}
//else{objCnt.innerText= maxL -objVal.length;}
else
{
var totalchar = parseInt((objVal.length - 1) / 160);
objCnt.innerText= maxL + objVal.length;
objtotmsg.innerText = totalchar + 1;
}
}
return true;
}
function createObject(objId)
{
if (document.getElementById) return document.getElementById(objId);
else if (document.layers) return eval("document." + objId);
else if (document.all) return eval("document.all." + objId);
else return eval("document." + objId);
}
</script>
<textarea id="TextArea1" onkeyup="return taCount(this,'charcount','totalmsg')" cols="20" rows="10"></textarea>
<asp:Label ID="charcount" runat="server" Text="0"></asp:Label>/<asp:Label ID="totalmsg" runat="server" Text="0"></asp:Label>
</asp:Content>
This is because the IDs get lengthened (their naming containers are pre-pended) when inside a master page, so instead of this:
taCount(this,'charcount','totalmsg')
You'll need this, which gets their actual rendered IDs:
taCount(this,'<%=charcount.ClientID %>','<%=totalmsg.ClientID %>')
If you view source in the browser and search for charcount or totalmsg when rendered in that master page, you'll see what I mean about the IDs, they'll probably look something like this: _ctl00_Content1_charcount.

Categories