I looked around in several forums for an answer to my problem, but I only found the solution in combination with a button.
I have to "translate" a website from Javascript to C# ASP because I have to store data in a SQL DB.
Now, I had a validation routine were the entries were checked before the data as sent by mail (that was in the old website, now it should be stored). One of the checks was only a warning (confirm) and not an error (alert). In JavaScript I did this with:
if (a > b){
Check = confirm("Are you sure your entry is correct?");;
if (Check == false){
return false;
}
}
Since I have many more checks before and after this part, I can't hook it to a button.
Is there a way to solve it like the alert? e. g.
<script type = "text/javascript" language = "javascript">
<asp:Literal id="ltlAlert" runat="server" EnableViewState="False"> </asp:Literal>
</script>
private void Say(string Message)
{
// Format string properly
Message = Message.Replace("'", "\\'");
Message = Message.Replace(Convert.ToChar(10).ToString(), "\\n");
Message = Message.Replace(Convert.ToChar(13).ToString(), "");
//Display as JavaScript alert (!)
ltlAlert.Text = "alert('" + Message + "')";
}
like:
private bool Ask(string Message)
{
// Code to display confirm from Javascript here
return;
}
I'm pretty new to C# (otherwise I programmed in VB, VBA and - Long ago - in COBOL) so I'm still trying to get my bearings.
Are you looking for something like the following where you can check several conditions before submitting a form? The button would call that JavaScript function.
function ValidateForm(){
if(email is invalid){
alert("Email is invalid");
return;
}
if(phone is invalid){
alert("phone is invalid");
return;
}
var Check = confirm("Are you sure your entry is correct?");
if (Check == false){
return false;
}
else{ Submit Form };
}
Related
I've been all over trying to find an answer to this, but every answer I found seemed to differ quiet a bit from what I really am looking for.
I need to check to make sure that two ASP Textboxes have been filled in before running a C# function that will do work on the text boxes.
Currently, I am using codebehind to check, but it is sloppy and has to postback to work.
So I have:
<td>Start Date (mm/dd/yyyy):</td><td><asp:TextBox ID="startDate" runat="server"></asp:TextBox></td>
<ajax:CalendarExtender ID="ce1" runat="server" TargetControlID="startDate"></ajax:CalendarExtender>
<td>End Date (mm/dd/yyyy):</td><td><asp:TextBox ID="endDate"></asp:TextBox></td>
<ajax:CalendarExtender ID="ce2" runat="server" TargetControlID="endDate"></ajax:CalendarExtender>
So I need a JS function to check if both field are empty, before using AJAX to run a C# program. I'm new to ASP and JS but this problem came through and figured it would be a (sort of) easy fix.
I would assume something like:
function checkDates(startid, endid) {
var s = document.getElementById(startid);
var e = document.getElementById(endid);
if( s != '' && e != ''){
//Use ajax to run C# function
}}
should work. But I can't seem to find any examples close to it to get an idea of what I need to do when working ASP and not just HTML.
Any input is greatly appreciated! (I tried to be as clear as possible, getting tunnel vision..)
You are almost there
function checkDates(startid, endid) {
var s = document.getElementById(startid);
var e = document.getElementById(endid);
if( s.value != '' && e.value != ''){
//Use ajax to run C# function
}
}
You should also need to check on the server side to ensure that the parameters being supplied are not null or empty.
This should work for you. I built an object to help keep things organized. Get the elements using the ClientID and store the reference in an object.
Whatever you're binding the handler to just needs to call Page.Handlers.CheckDates();
var Page =
{
Members:
{
startDate: document.getElementById('<%=startDate.ClientID %>'),
endDate: document.getElementById('<%=endDate.ClientID %>')
},
Handlers:
{
CheckDates: function ()
{
if (Page.Members.startDate.value.length > 0 && Page.Members.endDate.value.length > 0)
{
Page.Ajax.ValidateDates();
}
}
},
Ajax:
{
ValidateDates: function ()
{
//Put you ajax code here
}
}
}
In addition to Kami's answer I believe asp.net automatically prepends a tag to all asp.net controls to distinguish them. If you haven't changed it yourself I believe the default is "ct100_". So if you're using jQuery and aren't use an ajax call to get the ClientID the selector would look something like "#ct100_idname".
http://www.asp.net/web-forms/tutorials/master-pages/control-id-naming-in-content-pages-cs
Edit:
You can also use an inline server call to get the ID of a asp.net control
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
I have two pages
1. a.aspx and
2. b.aspx
I pass query string from "b.aspx?save=success" to a.aspx.
In Page Load of a.aspx I have the following code:
Page_Load()
{
if(!Postback)
{
if (Request.QueryString["save"] != null)
{
noDataFound.InnerHtml = "operation success";
}
}
}
Problem: On load of a.aspx page I get the message "operation success". This is Ok.But When I refresh the page again I get the same message as "operation success". How not to display again the same message on page refresh(pressing F5or reload).
function invokeMeMaster() {
var isPostBack = <%= Page.IsPostBack ? "true" : "false" %> ;
if (!isPostBack) {
/* START */
var query = getQueryParams(document.location.search);
var p = query.save;
if (sessionStorage.hits) {
sessionStorage.hits = Number(sessionStorage.hits) + 1;
} else {
sessionStorage.hits = 1;
}
if (p == "success" && (sessionStorage.hits) % 2 == 0) {
document.getElementById("<%=noDataFound.ClientID %>").innerText = "Testing...........";
}
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
/* END */
} else {
document.getElementById("<%=noDataFound.ClientID %>").innerText = "";
}
}
window.onload = function () {
invokeMeMaster();
};
untested solution (Keeping F5 or Reload of Page in mind), may be you have do something like below:
if(!IsPostBack)
{
if (Request.QueryString["save"] != null && Session["CheckSuccess"] == null)
{
noDataFound.InnerHtml = "operation success";
Session["CheckSuccess"] = "true";
}
else
noDataFound.InnerHtml = string.Empty;
}
The best I can think of is using the IsPostback property to check that.
if (!this.IsPostback)
{
// first try
if (Request.QueryString["save"] != null)
{noDataFound.InnerHtml = "operation success";}
}
NOTE: IsPostback is not set on refresh, only if clicking a button or something alike triggers the ASP.NET postback action.
The other thing you could do is set a Session variable then the 'operation succesful' must be shown (probably you determine this in another Page.
// other page
Session["showSaveMessage"] = true;
// this page
if (Session["showSaveMessage"] == true)
{
// show message
Session["showSaveMessage"] = false;
}
A third option is to move this client side. Create a javascript action on load of the page. When a specific part is added to the query string (#showmessage), you can catch that and show the message (How to get the value from the GET parameters?).
Then redirect to the parameterless version (#) by setting the url to the stripped version. Set window.location.href or window.location.search for that (this won't cause a call to the webserver, since it is all client side).
This circumvents the drawbacks of the first solution, but introduces more code client side. Luckily, ASP.NET MVC has some mechanisms for this. Unfortunately ASP.NET Web Forms doesn't have those.
I'll try to do the best I can to articulate what I'm trying to do.
Let me preface by saying that I am very new to C# and ASP.NET and have minimal experience with javascript.
I have a javascript function that invokes a prompt box. The overall picture is - if input is entered - it will be saved to a column in the database.
I'm drawing a blank on passing the value from the prompt box to the PostBack in c#.
function newName()
{
var nName = prompt("New Name", " ");
if (nName != null)
{
if (nName == " ")
{
alert("You have to specify the new name.");
return false;
}
else
{
// i think i need to getElementByID here???
//document.forms[0].submit();
}
}
}
This is what I have in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//I have other code that works here
}
else
{
//I'm totally lost here
}
}
I'm trying to figure out how to make that call for the input from the javascript function.
I've spent the last few hours looking online and in books. Been overwhelmed.
EDIT
i did a little tweeking to fit what I'm trying to do....
<asp:HiddenField ID="txtAction" runat="server" Value="" />
document.forms(0).txtAction.Value = "saveevent";
document.forms(0).submit();
trying to figure out how to insert the string into the table now.....
string nEvent = Request.Form["event"];
if (txtAction.Value == "saveevent") {
nName.Insert(); //am i on the right track?
}
Well, here's one possible way (untested but should give you the basic idea). You could place a hidden field on your form to hold the value of the prompt:
<input type="hidden" id="hiddenNameField" runat="server" value="">
Then prompt the user for the value, set it to the hidden field, and then submit your form:
document.getElementById('hiddenNameField').value = nName;
document.forms(0).submit();
Then in your code-behind you can just access hiddenNameField.Value.
if you are trying to call the method on the back side using the java script you can try using the web method approach.
for instance you have a function that will call the SendForm method
function SendForm() {
var name = $("#label").text();
PageMethods.SendForm(name,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
}
function OnFailed(error) {
}
and you have the method that will be called from javascript.
[WebMethod(enableSession: true)]
public static void SendForm(string name)
{
}
<script language='Javascript'>
__doPostBack('__Page', '');
</script>
Copied from Postback using javascript
I think you need AJAX request here. I suggest usage of jQuery, since do the dogs work for you... Otherwise, you will have to implement a lot of already written general code for AJAX processing.
Something as the following one:
function PromptSomewhere(/* some args if needed*/)
{
var nName = prompt("New Name", " ");
// Do process your prompt here... as your code in JS above. Not placed here to be more readable.
// nName is used below in the AJAX request as a data field to be passed.
$.ajax({
type: "post", // may be get, put, delete also
url: 'place-the-url-to-the-page',
data {
name: nName
// You may put also other data
},
dataType: "json",
error: PromptFailed,
success: OnPromptComplete
});
}
function PromptFailed(xhr, txtStatus, thrownErr) // The arguments may be skipped, if you don't need them
{
// Request error handling and reporting here (404, 500, etc.), for example:
alert('Some error text...'); // or
alery(txtStatus); // etc.
}
function OnPromptComplete(res)
{
if(!res)
return;
if(res.code < 0)
{
// display some validation errors
return false;
}
// display success dialog, message, or whatever you want
$("div.status").html(result.message);
}
This will enable you to send dynamically data to the server with asynchronous request. Now C#:
using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string nName = Request.Form["name"];
// do validation and storage of accepted value
// prepare your result object with values
result.code = some code for status on the other side
result.message = 'Some descriptive message to be shown on the page';
// return json result
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(result));
}
}
Notes: If you use ASP.NET MVC 2 or higher I think, you will be able to use JsonResult actions and Request.IsAjaxRequest (I think was the name), and many other facilities and improvements of ASP.NET - ASP.NET MVC is the new approach for creating web applications based on MVC pattern (architecture) and will replace ASP.NET Pages eventually in some time.
This is a very good resource and contains the answer to your question:
How to use __doPostBack()
Basically, call PostbackWithParameter() function from your other JS function:
<script type="text/javascript">
function PostbackWithParameter(parameter)
{
__doPostBack(null, parameter)
}
</script>
And in your code-behind, grab the value for that parameter like so:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
}
i can write methods like that
public void CompareEmail()
{
some code
}
public void UpdateEmail()
{
some code
}
public void InsertEmail()
{
some code
}
i am click the button onclientclick call the function like that
<asp:Button ID="btnSendNow" runat="server" CssClass="invdisp_btn" OnClick="btnSendNow_Click"
Text="Send Now" OnClientClick="return getEmailMessage()" />
java script function is like that
<script type="text/javascript" language="javascript">
function getEmailMessage()
{
var LoginID = document.getElementById('hdn').value;\\ i can pass 1 or 0
if (LoginID != 0)
{
//This place using CompareEmail() method How to write code comapare values not matching ask update confirm box
var ans;
ans = window.confirm('DO u want to update?');
if (ans == true)
{
// control.UpdateEmail();\\how to call UpdateMethod in .cs file
alert('updated');
}
else {
return false;
}
}
else {
var ans;
ans = window.confirm('DO u want to Insert values?');
if (ans == true)
{
PageMethods.InsertEmail();\\how to call InsertMethod in .cs file
// control.InsertEmail();
alert('Inserted');
}
else
{
return false;
}
}
}
</script>
how to write the code in java script function call the .cs file methods pls help me
Thank u
hemanth
You can achieve it by declaring your method as Web Methods in the code behind files.
Have look at this How to call a server-side method from client-side JavaScript !, it completely gives a solution to your problem.
Otherwise you can also use AJAx to do this.
You should try Pagemethods and ASP.net Ajax.
To call a server side method from client side, you have the following options:
Use ICallBackEventHandler
Use a Webservice with [ScriptService] attribute and call it's web methods from js
Use PageMethods. But that allows you to call static methods on your aspx page, only. Hence you won't be able to access any page controls.
I would recommend option 2, since it's the easiest.
I have two problem in my data entry page: probml 1)Though I am doing client side validation, why pointer is going to code behind page..
I have a text field called amount if that field is empty I am one alert message and focusing on that field. But immidieately control going to code behind page: in this line:
decimal amount = Convert.ToDecimal(txtAmount.Text);Here I am getting the exception, “Input paramater was not in correct format”
Here is javascript code:
<script type="text/javascript">
function validate()
{
var value = document.getElementById("txtAmount").value;
if(value=="")
{
alert("Please enterAmount.");
document.getElementById("txtAmount").focus();
return false;
}
else
{
return true;
}
}
</script>
<asp:Button ID="btnSave" runat="server" Text="Save" Width="64px" Font-Bold="true" OnClientClick="validate()" onclick="btnSave_Click"/>
Prblm2: While I am entering duplicate values I am expecting the message like “This id already exists, please try with another id”, but I am getitng the excetpion like primary key conflict……… Here is code for that..
if (!Page.IsValid)
return;
int sum = 0;
ContactPersonBO contactpersonbo = new ContactPersonBO();
string personid = txtPersonid.Text;
decimal amount = Convert.ToDecimal(txtAmount.Text);
try
{
contactpersonbo.PersonID = personid;
contactpersonbo.Amount = amount;
sum = ontactpersonbo.InsertPerson();
if (sum > 0)
{
lblMessage.Text = "person has been succesfully added.”;
}
else
{
lblMessage.Text = "This person already exists, please try with otherid”;
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message.ToString();
}
Note: Here control is never coming to this part:
else
{
lblMessage.Text = "This person already exists, please try with otherid”;
}
Concerning your first problem, you should return false from your onclick handler in order to prevent default processing to take place and the page to be submitted:
<asp:Button ID="btnSave" runat="server" Text="Save" Width="64px"
Font-Bold="true" OnClientClick="return validate()" onclick="btnSave_Click" />
Concerning your second problem, it looks like your InsertPerson() method is throwing an exception instead of returning 0 if the person already exists. From the code you posted below, it seems the method doesn't perform any check on the existence of the new person.You might want to add that test using e.g. a select query.
Probabily the txtAmound doesn't cointain a parsable sring (it could be empty or the decimal separator doesn't stick to the setting you are using)
you can use Decimal.TryParse instead.bear in mind it just doesn't raise the exception if the string is not in a correct format
http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx
for the second case I don't know you DAL(data access layer) but I can guess one the table/object you are trying to insert the person there is a primary key constrain.
Probably you are using an Id that has been already saved