How to call method of .aspx from .cs file - javascript

I created web page in that i used javascript in .aspx file.
I have a save-button,but in the source code i used javascript for save button, where i declared a function called OnClientClick="javascript : validateTextTest()" and in the head of source code i called this function validateTextTest().
Below is the save button in source code:
<asp:Button ID="Save" runat="server"
onclick="Save_Click" Text="Save"
OnClientClick="javascript : validateTextTest()" Width="63px" />
Now i need to call a function validateTextTest() in save button of .cs file.Because i have two to three textboxs, if i leave one texbox out of three textbox it should not insert into DB.
So please tell me how to call the function in .cs file.

Insted of doing such things , you can use asp.net validation controls , for your purpose you are going to need a RequieredFieldValidator for each one of your TextBoxes , and you can use them like following code :
<asp:TextBox ID="txtISBN" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RQVISBN" runat="server" ErrorMessage="*" ControlToValidate="txtISBN"></asp:RequiredFieldValidator>
These controls are greate ! And they do validation on clientSide as you want ;)

validateTextTest is your javascript function which you probably use for some client side validations before submitting to the server. So i dont think you really should use the client side function in your sever side code (.cs file) to validate the input. You should do the same validation inside your server side code also. Something like this
if((!String.IsNullOrEmpty(TextBox1.Text)) &&
(!String.IsNullOrEmpty(TextBox1.Text)) &&
(!String.IsNullOrEmpty(TextBox1.Text)))
{
// Insert to DB
}
else
{
//Show validation error message
}

You need to firstly start off by defining the technology stack you are using. Is it ASP.NET or MVC.
I am assuming you are using ASP.NET. Given the way you have already started writing this application. You will need to do a few things to get your approach to work.
<form name="myform">
<asp:HiddenField runat="server" id="validRequest"/>
<script type="text/javascript">
function validateTextTest() {
//validation goes here
var validRequest = document.getElementById(<%#validRequest.ClientID%>);
//set validation outcome to the validRequest etc
validRequest.value = 'true';
if(validRequest.value == 'true')
return true;
return false;
} </script>
</form>
I forget which one it is but check either your Page_Load etc
protected void Page_Load(object sender, EventArgs e)
{
if(validRequest.Value == "true")
//Do whatever you need to
}

Related

How do I call a C# method using JavaScript in .NET Framework 4.7.2?

Whenever the textbox value changes a C# method should be called. The textbox uses a calendar validator so when a user changes the date it should count as a value change. The date can be changed by clicking on a new date or typing it in. Typing it in can possibly call the method multiple times which is fine. How can I activate a C# method whenever a textbox value is changed using JavaScript in .NET Framework 4.7.2?
.ascx file:
<script type="text/javascript">
$(document).ready(function () {
$("#textBox1).change(function () {
// How can I call the buttonClick method?
}
});
</script>
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="date" runat="server" ControlToValidate="textBox1"
ErrorMessage="Date Required" CssClass="field-validation-error"></asp:RequiredFieldValidator>
<ajax:CalendarExtender ID="ceDate" runat="server" TargetControlID="textBox1" />
.ascx.cs file:
protected void buttonClick(object sender, EventArgs e)
{
//...
}
I tried doing this without JavaScript. There is an OnTextChanged event listener that should call the buttonClick method. This has not been working for me. Clicking on a new date or typing in the textbox doesn't trigger the method. It only seems to trigger when I press the 'Enter' key. The event listener should not depend on the 'Enter' key being pressed.
.ascx file:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick"></asp:TextBox>
<asp:RequiredFieldValidator ID="date" runat="server" ControlToValidate="textBox1"
ErrorMessage="Required" CssClass="field-validation-error"></asp:RequiredFieldValidator>
<ajax:CalendarExtender ID="ceDate" runat="server" TargetControlID="textBox1" />
Method 1:
<script type="text/javascript">
$(document).ready(function () {
$("#textBox1").change(function () {
<%= Page.ClientScript.GetPostBackEventReference(textBox1, "") %>
}
});
</script>
But take care that under certain circumstances, the id value of the text box control will not necessarily be the same as the ID (name) of the textbox control on the server side. One way to make sure that your jQuery selector uses the correct value for the id of the textbox control is to use the ClientID property of the server-side object, like so:
<script type="text/javascript">
$(document).ready(function () {
$("#<%= textBox1.ClientID %>").change(function () {
<%= Page.ClientScript.GetPostBackEventReference(textBox1, "") %>
}
});
</script>
Or if you don't want to bother with using the ClientID property, then you can set the value of ClientIDMode attribute on the mark-up of the control to Static, then the id on the server and client will always be the same, like so:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick" ClientIDMode="Static"></asp:TextBox>
However, it is not advisable to use ClientIDMode="Static" within custom user controls, since you could end up with multiple elements with the same ID on the client when the control is used multiple times on the same page.
Method 2:
It is also possible to achieve all this without using JavaScript.
The buttonClick server-side event handler will not be called until the form is posted back to the server-side.
One way to automatically do a post-back to the server whenever the text is changed is by adding the AutoPostBack="true" attribute to the mark-up of the textBox1 control:
<asp:TextBox ID="textBox1" runat="server" OnTextChanged="buttonClick" AutoPostBack="true"></asp:TextBox>
Side-note: Remember, doing a post-back will cause the whole page/control life-cycle to be executed, even if your controls are within an <asp:UpdatePanel>...</asp:UpdatePanel> block (for asynchronous/ajax updates), so things like the Page_Load function will be run every time there is a post-back. If you have initialization code within such functions and you don't want to re-initialize on every post-back, just check that the Request is not post-back before running initialization code, i.e:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// initialization
}
}

Trigger jQuery function / event from c# code-behind

I hope I will be able to explain my problem clearly.
Scenario:
Asp.net web page with UpdatePanel. Some properties of controls are changeable via UI trigger and are set in jQuery (for faster response, as this page is expected to accept input data of at least 500 records per day).
Example below, (if written in c# code, the logic is like this: txtIDNumber.Enabled = chkIsReceiptRequired.Checked; rfvIDNumber.Enabled = chkIsReceiptRequired.Checked;):
Markup:
<asp:CheckBox ID="chkReceiptRequired" runat="server" Text="Receipt required" />
<asp:TextBox runat="server" ID="txtIDNumber" Width="150px" style="float: left;" />
<asp:RequiredFieldValidator ID="rfvIDNumber" runat="server" ForeColor="Red"
ErrorMessage="Enter ID No." ControlToValidate="txtIDNumber" ValidationGroup="save" />
Snippet of default jQuery code (upon page load, chkReceiptRequired is unchecked, validator and textbox will only be enabled upon ticking chkReceiptRequired):
<script type="text/javascript">
function pageLoad(){
$('input[id$=_txtIDNumber]').prop('disabled', true);
ValidatorEnable($("[id$='rfvIDNumber']")[0], false);
$('input[id$=_chkReceiptRequired]').change(function () {
$('input[id$=_txtIDNumber]').prop('disabled', !$(this).is(':checked'));
$('input[id$=_txtIDNumber]').val(!$(this).is(':checked') ? '' : $('input[id$=_txtIDNumber]').val());
ValidatorEnable($("[id$='rfvIDNumber']")[0], $(this).is(':checked'));
});
}
</script>
I'm using this same page to load the data here to perform record update. Code snippet of data loading:
var maintableComponent = new MainTableComponent();
var maintableData = maintableComponent.GetMainTableDataById(rowId);
chkReceiptRequired.Checked = maintableData.IsReceiptRequired.Value;
txtIDNumber.Text = maintableData.IDNumber;
//todo: enable txtIDNumber and rfvIDNumber from here
The problem: by right, upon page render for update, because chkReceiptRequired is checked, supposedly txtIDNumber should be enabled. But my problem is, it is not. What can I do to enable the txtIDNumber and rfvIDNumber upon data loading from code-behind?
*I have already tried this link and this but it doesn't seem to work.
Please, please help me. The snippets I posted here are just one of many jQuery validations that I desperately need to address. Thanks in advance.
Feeling incredibly stupid right now. Figured out how to fix it after sleeping it off. :P
I just changed the default jQuery code to this:
var isReceiptRequired = $('input[id$=_chkReceiptRequired]').is(':checked');
$('input[id$=_txtIDNumber]').prop('disabled', !isReceiptRequired);
ValidatorEnable($("[id$='rfvIDNumber']")[0], isReceiptRequired);
I just remembered that the last thing in the page-cycle is rendering it on the page so the jQuery can be manipulated by the values set in the control from code-behind.

Unable to get property 'value' of FileUpload in a UserControl using javascript

I have a UserControl (with FileUpload) included on a Master Page as follows:
Master Page
<uc:uploadFiles ID="UC1" runat="server"/>
uploadFiles.ascx
<script type="text/javascript">
function ValidateUpload() {
var FileUpload_function = document.getElementById('myfile');
if (FileUpload_function.value == '') {
return false;
}
else {
//do stuff }
return true;
}
</script>
<div id="div_FileUpload" class="FileUpload_content" runat="server">
<asp:FileUpload ID="myfile" class="FileUpload" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="myfile" ClientValidationFunction="ValidateUpload" />
</div>
When I run the page I get the following error caused by the CustomValidator:
Unable to get property 'value' of undefined or null reference.
My guess is that the FileUpload value is validated before the entire page is rendered because when I delete the UserControl and move the codes to the MasterPage directly, the CustomValidator works fine.
How can I solve the problem?
You need to use .ClientID in document.getElementById. Becasue when you use that in user control, cotnrol id - myfile might be renamed to something else, like ct00_myfile and in that case if you execute same js code, it will give you null.
You need to use following js code.
var FileUpload_function = document.getElementById('<%=myfile.ClientID %>');

How do I pass values from javascript (innerhtml) to asp.net codebehind without hidden input field?

I have an aspx page (mainpage), that I use to populate some divs on another aspx page (popup) on button click using the window.loaded event. Code is below:
Script on mainpage.aspx
<script type="text/javascript">
window.callback = function (doc) {
if (document.getElementById('GridView2') != null)
{
// Get Gridview HTML and wrap it with <table> tag
var temp = document.getElementById('GridView2').innerHTML;
var temp2 = "<table>" + temp + "</table>";
doc.getElementById('foo').innerHTML = temp2; // this works fine
}
else
{
// GridView is missing, do nothing!
}
}
function openWindow() {
// Only open a new Compose Email window if there is a Gridview present
if ((document.getElementById('GridView2') != null)) {
var mywindow = window.open("Popup.aspx");
}
else {
alert("Please create GridView first");
}
}
Code on Popup.aspx
<script type="text/javascript">
function loaded() {
window.opener.callback(document);
alert(document.getElementById('foo').innerHTML); //This alerts the code I need
//var input = document.createElement("input");
//input.setAttribute("type", "hidden");
//input.setAttribute("name", "testinput");
//input.setAttribute("runat", "server");
//input.setAttribute("value", document.getElementById('foo').innerHTML);
////append to form element that you want .
//document.getElementById("foo2").appendChild(input);
}
</script>
<asp:Button OnClick="Send_Email_Button_Click" ID="SendEmail" Text="Send Email" CssClass="Button1" runat="server" />
<div id="foo" runat="server">
</div>
Popup.aspx.cs
protected void Send_Email_Button_Click(object sender, EventArgs e)
{
string subject = String.Format("TEST EMAIL");
string mailto = "me#mysite.com";
string mailfrom = Environment.UserName + "#mysite.com";
string mailBody = "<h1>Testing</h1>";
MailMessage mail = new MailMessage(mailfrom, mailto, subject, null);
mail.IsBodyHtml = true;
mail.Body = mailBody;
SmtpClient smtpClient = new SmtpClient("smtphost");
smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
}
}
Now, I'm stuck trying to pass the value of the div.innerhtml to codebehind, so I can create an email with this HTML markup. I tried using a hidden div, but I got an asp.net error about Request Validation: html code in an input field, which is a fair point. I can't seem to access div.InnerHtml. I get the value "\r\n\r\n". I have the value I need, but it's in Javascript, I just need a way to get this value to C# so I can send an email.
When I click on the SendEmail button, I get the alert again (because window.loaded is being called). How can I make it so that the Popup.aspx is only populate once, and not at every button click? And how to pass the innerhtml value to get SendEmail to work? Thanks so much for looking.
To send some data to code behind you have two methods. The Post and the Get.
The one is to send data with post back - meaning that you need to add them inside a hidden or other input control that send them with post.
The other is to add them to the url, as parameters.
Both of this methods can be used with ajax call. So select one and send your data to code behind.
About the message:
Request Validation: html code in an input field
This is security measure for general purpose, in your case if you know that you going to send html code on code behind, and you know how you control that, simple disabled it and do not worry - just be careful what you going to render later.
From MSDN Request Validation in ASP.NET:
This can be a problem if you want your application to accept HTML
markup. For example, if your site lets users add comments, you might
want to let users perform basic formatting using HTML tags that put
text in bold or italics. In cases like these, you can disable request
validation and check for malicious content manually, or you can
customize request validation so that certain kinds of markup or script
are accepted
Update
example code that works:
Main page
<head runat="server">
<title></title>
<script type="text/javascript">
window.callback = function (doc) {
doc.getElementById('SendBack').value = escape("<b>send me back</b>");
}
function openWindow() {
var mywindow = window.open("Page2PopUp.aspx");
}
</script>
</head>
<body>
<form id="form1" runat="server">
open pop up
</form>
</body>
</html>
PopUp Page
<head runat="server">
<title></title>
<script type="text/javascript">
function GetDataBack() {
window.opener.callback(document);
}
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
<input id="SendBack" name="SendBack" value="" type="hidden" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" OnClientClick="GetDataBack()" />
<asp:Literal runat="server" ID="txtDebugCode"></asp:Literal>
</div>
</form>
</body>
</html>
and read it :
protected void Button1_Click(object sender, EventArgs e)
{
txtDebugCode.Text = Server.UrlDecode(Request.Form["SendBack"]);
}
So after a half day of breaking my head over this, I finally worked around dealing with client and server scripts by using just code-behind. I had never heard of Server.Transfer and Page.PreviousPage, so it serves me right, but it turns out it's just what I needed.
There is an excellent msdn article here that explains the concept in detail, but suffice it to say that you can access the previous page's controls if you use Server.Transfer to open the new page. Now I thought my troubles ended there, but apparently Server.Transfer is ancient and messes with the way UpdatePanel handles postbacks. Another brilliant article explaining problems and workarounds is here. I used the msdn article on PostBackTrigger to finally get my code to work.
And finally, mad props to Aristos, he sat and helped me through this, so I'm going to mark his answer as the right answer--since mine's an alternative and not the answer to my question. That's all, folks!

getElementById not finding control generated by ASP.net

I am simply trying to store a label in a variable in javascript but for some reason this isn't working with document.getElementById('control');. I know my javascript is linking to my html file fine because everything else works.
Here is my javascript code:
function performEvapCooledCircuit(txt)
{
var error = document.getElementById('lblError');
if (txt.value == null || isNaN(txt.value))
{
error.style.visibility = "visible";
}
}
Here is the html code for my label:
<asp:Label ID="lblError" class="NormLabel" runat="server"
style="color:red; visibility:hidden;" Text="Invalid Input."></asp:Label>
I am getting an error that says object expected??
The ID that ASP.NET will generate will not be "lblError" so you'll need to reference it by its ClientID
document.getElementById('<%=lblError.ClientID %>');
If your javascript file is external I've usually had to write a type of "Init" javascript method to make sure my ID's were set up property
On your ASPX page:
<script type="text/javascript">
var lblError = null;
function InitializeVariables()
{
if (lblError == null) // make sure you only do this once
{
lblError = document.getElementById("<%=lblError.ClientID %>");
}
}
</script>
<asp:Label
ID="lblError"
class="NormLabel"
runat="server"
style="color:red; visibility:hidden;"
Text="Invalid Input."></asp:Label>
Then in your javascript file you'll have to call InitializeVariables() to make sure you've got the variables pointing to the proper asp.net controls
function performEvapCooledCircuit(txt)
{
InitializeVariables();
if (txt.value == null || isNaN(txt.value))
{
lblError.style.visibility = "visible";
}
}
"hunter" gives a pretty solid way of doing things, however a, in my opinion far better method is to use the "CliendIDMode" property on the control and set that property to "Static". This will make the client and server IDs the same. Like this:
<asp:TextBox ID="ServerAndClientId" runat="server" ClientIDMode="Static" />
The ID of the label is not "lblError". The ASP.net engine changed the ID. Check the HTML source code in the browser to find out the real ID.
That's not HTML for the label, that is an ASP.NET Control which will be rendered into HTML before it is sent in the response. ASP.NET WebForms controls sometimes change the id for the HTML they create.
View the source of the webpage to see what the id for the HTML element is on the rendered page.
You can use this:
document.getElementById('<%= lblError.ClientID %>').click()
Starting from ASP.NET 4.0 you can use ClientIDMode property for you element. And if you set it into Static then the ClientID value will be set to the value of the ID property:
<asp:Label ID="lblError" runat="server" ClientIDMode="Static" />
will be rendered as something like this:
<span id="lblError" name="ctl00$MasterPageBody$ctl00$Label1" />

Categories