Can't call alert from Server Side - javascript

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

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);
}

RegisterStartupScript only runs the first time. ASP.NET C# 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

Sending java script variable value as part of PostBackUrl query string

I need to send a parameter value into a query string of a PostBackUrl method
within asp button.
The value I need is already being captured within a java script function shown below.
How do I send the value in hiddId as part of URL ? The below method isn't working. Can someone please help ?
<script language="javascript" type = "text/javascript">
function btn_Selected() {
var hiddId = null;
$('#<%=GridView1.ClientID %>').find('input[type=radio]:checked').each(function () {
hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
});
}
<asp:Button ID="Btn_Update" runat="server" Text="Update" PostBackUrl="Screen_Edit.aspx?CustID='<%=hiddId%>'"
Instead of a post-back, just redirect using JavaScript.
function btn_Selected() {
var hiddId = null;
$('#<%=GridView1.ClientID %>').find('input[type=radio]:checked').each(function () {
hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
});
window.location.href = "Screen_Edit.aspx?CustID='" + hiddId + "'"
}
If you look at the HTML source of the page, the button will have an javascript onclick event that looks something like this javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$mainContentPane$Btn_Update", "", false, "", "Screen_Edit.aspx?CustID=", false, false))
All we have to do is find a way to insert your variable after ?CustID=.
You can replace the onclick value of the button with the .attr() function of jQuery and do a search and replace to insert your variable.
<script type="text/javascript">
$(document).ready(function () {
var hiddId = $(this).closest('tr').find('input[type = "hidden"]').val();
$("#<%=Btn_Update.ClientID %>").attr("onclick", $("#<%=Btn_Update.ClientID %>").attr("onclick").replace("?CustID=", "?CustID=" + hiddId));
});
</script>

how to call javascript client side function from code behind file

How would I call showItems() function in aspx page from code behind.
<script>
function getItems(){
var items = [];
return items; //items=['a','b','c']
}
<form id="form1" runat="server">
<asp:Hiddenfield id="HiddenField1" runat="server"></asp:hiddenfield>
</form>
code behind:
ScriptManager.RegisterStartupScript(this, GetType(), "items", "<script type='text/javascript'>getItems()</script>", false);
A few things here...
First, you don't "call a client-side function from server-side code." What you can do is include some client-side code which itself will call the function, client-side. Which appears to be what you're doing, but I just want to make sure you understand the difference.
Second, your function is called showItems, but you're calling a function called getItems:
<script type='text/javascript'>getItems()</script>
Call showItems() instead? Like this?:
ScriptManager.RegisterStartupScript(this, GetType(), "items", "<script type='text/javascript'>showItems()</script>", false);
Third, the showItems function returns something. But you're not actually doing anything with that result. You're simply invoking the function and ignoring the result. So it's not really clear what you're trying to accomplish.
Like this:
Page.ClientScript.RegisterStartupScript(GetType(), "key", "showItems();", true);
Edit: To get the javascript return value at C# code behind Assign the values to the hidden control using the javascript code. Then you can access the Hidden control value in C# code. Take a look at this article. for example:
<script type="text/javascript">
function showItems() {
var items = new Array(3);
items[0] = "name1";
items[1] = "name2";
items[2] = "name3";
items[3] = "name4";
document.getElementById('<%=HiddenField1.ClientID%>').value = items.join(',');
}
</script>
And in the code behind:
string[] itemArr = HiddenField1.Value.Split(",".ToCharArray());

Async Javascript callback not triggering the RaiseCallBackEvent function

In my asp.net application I used the async javascript callback.
The requirement is once the user enters the Postal code an async javascript callback function should be called. And the server side code must return me the city with respect to the postal code.
The coding I did is:
<asp:TextBox ID="txtPostCode" runat="server" CssClass="textbox" onchange="javascript: getCityAndStreet();" BorderStyle="Ridge" Height="20px" style="margin-left: 10px" Width="442px"></asp:TextBox>
This textbox onchange it will call the javascript function getCityAndStreet()
function getCityAndStreet()
{
var postalCode = document.getElementById('<%=txtPostCode.ClientID%>');
CallServer(postalCode.value, "");
}
function ReceiveCityAndStreet(rValue,context)
{
alert(rValue);
var city = document.getElementById('<%= txtCity.ClientID%>');
city.value = rValue;
}
Here the CallServer is the server side runtime javascript which is registered as below
protected void Page_Init(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCityAndStreet", "context",true);
String callbackScript;
callbackScript = "function CallServer(arg, context)" + "{ " + "alert('Entered inside CallServer' + arg);" + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
}
I implemented the ICallBackHandler and by this I got 2 methods:
string ICallbackEventHandler.GetCallbackResult()
{
return cityAndStreet;
}
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
txtStreet.Enabled = true;
txtCity.Enabled = true;
cityAndStreet = eventArgument;
}
in page_load function I just disabled the txtStreet.Enabled. txtCity.Enabled text boxes and on the raise callbackevent I am enabling it.
The issue here is the RaiseCallBackEvent is not working. I mean its not been triggered implicitly.
(This application is not accessed directly in the browser it is accessed through the SharePoint site)
I think the problem is that your button actually does postback when you click on it. You do not need postback because you are calling server using AJAX. Try changing onchage handler to this:
onchange="getCityAndStreet();return false;"
This will cause your button not to trigger postback.
EDIT: Also i want to mention that you cannot change controls in RaiseCallBackEvent method. It is not an actual postback. You need to enable text fields using javascript in onSuccess method.

Categories