Not waiting for Javascript function respone from code behind - c#

Hi I have a scenario,
I have a list I need to save that into table before saving that I need to check that already exist or not if exist I need to show dialog to user Are you sure need to override (YES Or NO).these thing I need to do in code behind in web. before getting response(Yes or No) from user I need to wait if yes need to execute one function otherwise no execution.
I do the following in Code behind:
int dupCount = checkdup(id);
// Get Conformation From the User Need to Save OR Not
if (dupCount > 0){
System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "confirm", "<script>Confirm();</script>", false);
Thread.Sleep(8000);
string confirmValue = hdnConform.Value;
if (confirmValue == "Yes"){
savemethod();
}
else { }
}
else{
savemethod();
}
In the design, I do this:
function Confirm() {
if (confirm("Do you want to save data?")) {
document.getElementById('<%=hdnConform.ClientID %>').value = "Yes";
} else {
document.getElementById('<%=hdnConform.ClientID %>').value = "No";
}
}
Now I come to the issue. While executing this, my javescript function is called very last and my code does't wait for user response (Yes or No), it is executing continually.

I suggest you a refactor of your code in this way. Call server side function only if the user wants to save data.
function Confirm() {
if (confirm("Do you want to save data?")) {
$.ajax({
url: 'your method url',
type: "POST",
//other parameters
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
} else {
//other code
}
}
I think that Thread.Sleep for this purpose is unuseful

Related

In C# can we check if a duplicate value is entered

I have a grid view where I'm trying to insert a new value. Before doing an insert need to check if the value entered already exists in DB (cannot be duplicate).
The column that needs to be checked for duplicate is of type varchar which can accept maximum characters in a string (it can have spaces and can also have other special characters - it is basically a sentence).
E.g. Insert specific job-related impacts: (for example, impacts to customer or client service)
We cannot make this column unique in SQL server as it is declared as varchar(max).
Can we perform a check for a large string like this from C#?
The primary concept is as follows:
private void dataGridView1_CellValueChanged_1(object sender, DataGridViewCellEventArgs e)
{
int columnToCheck = 0;//The index of the property/field/column you want to check
if (e.ColumnIndex == columnToCheck)
{
using (var DB = new DataContext())
{
if (DB.YourTable.Where(v => v.id == dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()).Count > 0)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
MessageBox.Show("This key already exists");
//Return the error message to your javascript in asp.net here
}
}
}
}
In a website however, you'd have to make an ajax call, so whichever datatable you're using, find its event which would similar to dataGridView's CellValueChanged event. If you fail to do so, try adding the onchanged="" tag to its HTML element definition e.g. <table class="table" id="tab" onchanged="eventfunction(this)"></table> and in your javascript, handle the call like the following:
function eventfunction(element)
{
//Use an ajax call to your controller from here
var id = document.getElementById(element.id).innerText; //or however you can obtain the active cells' value
$.ajax({
url: "/api/ControllerName/ActionName",
method: "POST",
data: id,
success: function (response)
{
//Handle the return call here
},
error: function (response)
{
//Or here if you return an error message
}
});
}
Or you can use jQuery's event handling like this:
$("#tab").on("onchange", function()
{
//Your code here
});
You controller can look like this:
[HttpPost]
public Customer GetCustomer(string id)
{
//LINQ Where validation here
}

Asp.net Ajax pageMethods not triggering success event handler

I have asp.net ajax page method like following,
[WebMethod]
public static string UnAuthVote(string vf)
{
return "";
}
and I am calling it like this,
PageMethods.UnAuthVote("alikhan", success1, error);
And my success1 and error method written like following,
function success1(response) {alert("");
return false;
}
function error(error) {alert("error");return false; }
The problem is it's invoking error event. Why my code is not calling pagemethod's success event.
help
Thanks
Well, I was using url rewriting. So that's why my pagemethods was not working.
Well
I set set_Path property like following
PageMethods.set_path("Auth/profile.aspx")
Now it's working as it should
It helps if you show the actual error, for example:
function success1(response)
{
alert(response);
}
function error(error)
{
alert(error);
}
You can also use a debugger or developer tools to identify the problem. The error may show on the Console tab. The debugger will allow you to troubleshoot more efficiently than editing code to show alerts but I understand that in some cases this is preferable. You can also write to the console by doing:
function success1(response)
{
if(window.console) console.log(response);
}
function error(error)
{
if(window.console) console.log(error);
}
The benefit of this is it doesn't get in the user's way, and is only visible if the console is open. Checking for window.console avoids exceptions thrown from logging to console if it is unavailable.
If you don't know the properties of the return objects you can iterate through them like this:
function error(error)
{
var output = [];
for(key in error)
{
output[output.length] = key.toString() + " = " + error[key];
}
alert(output.join('\n'));
}

C# ASP Confirm Pop Up (Again)

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

how to pass a variable to a Page Method Success callback function

i'm using asp.net PageMethods.So here is the way i make a call to the method from javascript
function hello()
{
var a =10;
PageMethods.SaveData(JSON.stringify(basicInfo), SaveSuccessCallback, SaveFailedCallback);
}
And here is my success call back condition
function SaveSuccessCallback(response) {
//handle success code here
ShowEdit();
}
Now i wanted to handle the ShowEdit() based on a variable a which is in the hello function.
The issue is i don't know if its possible to pass a from hello to SaveSuccessCallback .
Note: i can't make a global.
You can use a closure:
var a = 10;
PageMethods.SaveData(
JSON.stringify(basicInfo),
function(response) {
SaveSuccessCallback(response);
ShowEdit(a);
}, SaveFailedCallback);
function SaveSuccessCallback(response) {
//handle success code here
}
You may prefer to make this a bit cleaner by wrapping up the closure in another method:
PageMethods.SaveData(
JSON.stringify(basicInfo), SaveSuccessCallback(10), SaveFailedCallback);
function SaveSuccessCallback(a) {
return function(response) {
//handle success code here
ShowEdit(a);
};
}

Passing prompt box value from javascript function- PostBack to c#

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"];
}

Categories