jQuery progress bar until save in database asp.net - c#

In an Asp.Net application I need the jQuery progress bar that runs till the data is not saved in database
For this I created a web service and the Ajax jQuery function and the progress bar Javascript plugin
HTML
<div id="progressbar"></div>
<div id="result"></div>
<asp:Label runat="server" ID="lbldisp" Text= "Percentage Completed : "/>
<asp:Label runat="server" ID="lblStatus" />
<asp:Button ID="btnSave" runat="server" Text="Save" class="buttonstyle" />
Script (I am using Sys.Application.add_load instead of document.ready function due to DOM Interruption )
<link type="text/css" href="CSS/ui.all.css" rel="stylesheet" />
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script src="js/ui.core.js" type="text/javascript"></script>
<script src="js/ui.progressbar.js" type="text/javascript"></script>
<script type="text/javascript">
Sys.Application.add_load(function() {
// jquery Progress bar function.
$("#progressbar").progressbar({ value: 0 });
$("#lbldisp").hide();
//button click event
$("#ctl00_ContentPlaceHolder1_btnSave").click(function() {
$("#ctl00_ContentPlaceHolder1_btnSave").attr("disabled", "disabled")
$("#lbldisp").show();
//call back function
var intervalID = setInterval(updateProgress, 250);
$.ajax({
type: "POST",
url: "JobCard.aspx/InsertData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#progressbar").progressbar("value", 100);
$("#lblStatus").hide();
$("#lbldisp").hide();
$("#result").text(msg.d);
clearInterval(intervalID);
}
});
return false;
});
});
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
$("#lblStatus").text((value + 1).toString() + "%");
}
}
</script>
Web service
[System.Web.Services.WebMethod]
public static string InsertData()
{
fortest jobcardForm = new fortest();
//this is a line 760 --> jobcardForm.Insert_OilService();
jobcardForm.Insert_TuningService();
jobcardForm.Insert_OtherServices();
jobcardForm.Insert_QRCService();
jobcardForm.Insert_problemTaken();
jobcardForm.Insert_ActionTaken();
jobcardForm.Insert_SpareParts();
//Insert_Technician();
dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter insertjobcard = new dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter();
string a = insertjobcard.Insert_JobCarRegistration(
jobcardForm.txtdate.Text, jobcardForm.txtTimeIn.Text,
jobcardForm.txtTimeOut.Text, jobcardForm.Txt_RegNo.Text,
jobcardForm.Txt_FleetNo.Text,
jobcardForm.chkbkdvechle.Checked, jobcardForm.chkwalkin.Checked,
jobcardForm.chkRepeatJob.Checked,
jobcardForm.txtCustomerName.Text, jobcardForm.txtRiderName.Text,
jobcardForm.txtPhoneNo.Text, jobcardForm.txtEmail.Text,
Convert.ToInt32(jobcardForm.ddl_ServiceAdvisor.SelectedValue),
Convert.ToInt32((jobcardForm.ListBox1.SelectedValue == "" ? "0" : jobcardForm.ListBox1.SelectedValue)),
jobcardForm.ddl_Model.SelectedValue,
jobcardForm.ddl_type.SelectedValue, jobcardForm.txtKMSRUN.Text,
jobcardForm.ddl_color.SelectedValue
, "1", HttpContext.Current.Session["user_id"].ToString(),
jobcardForm.txtdateout.Text, jobcardForm.txtchassis.Text,
jobcardForm.ddlyear.SelectedValue, jobcardForm.txtexpirydate.Text,
jobcardForm.txtnotes.Text,
jobcardForm.ddllocation.SelectedValue).ToString();
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl);
return "Save Completed...";
}
Looks like the script is working fine but I am getting an error in the web browser console Window and the error is "500 Internal Server Error" at line 760 in web service jobcardForm.Insert_OilService();. But when I use the web service code in server side onclick event the data is inserted into the database. I need the progress bar, that's why I have to change the logic using web service
ERROR
I normally create an object of a class to use it in a static method and this was the simplest way to use a non-static method in a static method.

Why dont you do something like this:
function FunctionName() {
$.ajax({
type: "POST",
url: ,
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#progress-bar").show();
$("#progress-bar1").hide();
},
complete: function () {
$("#progress-bar").hide();
$("#progress-bar1").show();
},
success: function () {
}
});
}
And have 2 div
<div class="gap"></div>
<div id="progress-bar" style="display:none;">
<img src="~/Images/ajax-progressbar.gif" />
</div>
<div id="progress-bar1"></div>
</div>
So before you send your request you show $("#progress-bar").show(); once once the content loaded you hide it. Hope this answer your question.

Related

Struggling to ASP.NET C# Ajax novice question

I changed the code with a simple like these
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#RadioButtonYes').click(function () {
var enterdata = document.getElementById("RadioButtonYes").value;
$.ajax({
type: "GET",
url: "radiobutton03ask.aspx/SyncData",
contentType: "application/json charset=utf-8",
dataType: "json",
data: { 'data': enterdata },
success: function (response) {
text1 = "ajaxyes";
alert(text1);
},
failure: function (response) {
alert(response.d);
}
});
});
$('#RadioButtonNo').click(function () {
var enterdata = document.getElementById("RadioButtonNo").value;
$.ajax({
type: "GET",
url: "radiobutton03ask.aspx/SyncData",
contentType: "application/json charset=utf-8",
dataType: "json",
data: { 'data': enterdata },
success: function (response) {
text2 = "ajaxno";
alert(text2);
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
<div>
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server" Checked="true" GroupName="G" />
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server" GroupName="G" />
</div>
.cs side
I tried to add some debugging messages, but it didn't work.
public partial class Radio_Button__radiobutton03ask : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public void SyncData(string data)
{
if (data != "")
{
if (data == "RadioButtonYes")
{
Response.Write("SyncDataYes");
//return RadioButtonYes;
}
else if (data == "RadioButtonNo")
{
Response.Write("SyncDataNo");
//return RadioButtonNo;
}
else
{
Response.Write("SyncDataOther");
}
}
}
}
I am helping the company to debug some old projects(C# webforms), but struggling to simple ajax.
The goal is when pressing the radio button run ajax "ajaxyes" and .cs "SyncDataYes" message normally, but the above code does not respond when pressed.
I have tried alot of fixes i found online but none seem to work well for, if someone could help, it would be greatly appreciated.
first, there is a LOT of issues here.
first up:
[WebMethod]
public void SyncData(string data)
Why are you marking/making the routine as "void". Void of course in c# means that the function will NOT return anything!!!! - That should be a first obvious issue!
And since you using this inside of the web page (as opposed to a separate asmx page? Then you need to set the routine as static - since NO page class instance will have been created here (there is NOT post back).
next up:
Response.Write("SyncDataNo");
WHY would you try and use Response.Write? Response write is ONLY for writing into a web page. But the WHOLE IDEA of ajax is the web page is not and will not be sent up to the server for code behind to operate on. So, response write does not make sense AT ALL here! It can't be used, and you can EVEN see that the compiler does not allow this (now that you fixed and removed the void from that routine).
A so called "ajax" call?
The idea here is that you do NOT have to post back the web page. This is great since you don't get the browser "spinner" and all that waiting time. It also great since it runs VERY fast since you don't and are NOT posting the web page back to the server.
Of course the big downside is then the code behind can't see nor use, nor modify any of the controls on the web page. (since the web page is still sitting on the users desktop). So code behind for a web method can't see nor modify controls on the page (the calling JavaScript and ajax call HAS do to that change of controls).
So, lets use all of the above information, and fix this code.
Lets make a simple C to F temperature converter.
So, first up, that web method is to return a value, so we remove the void.
next up, as I stated, the page class "instance" is NOT re-created when we call such a web method, so that method ALSO MUST be marked as static. (I assume you know what that means, right???).
Ok. So the web method should look like this:
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static Double ConvertToC(Double MyC)
{
Double CelResult = (MyC * 1.8) + 32;
return CelResult;
}
So, we HAVE to make this routine static. (the page class is not re-reated, and the web page is STILL sitting on the users desktop).
So, say our markup looks like this:
<div style="text-align:right;width:20%">
<label style="font-size:large">Enter Celsious Tempature</label>
<asp:TextBox ID="txtC" runat="server" style="font-size:large;margin-left:5px;text-align:center"
TextMode="Number" Width="80px" Wrap="False"
ClientIDMode="Static">
</asp:TextBox>
<br /> <br />
<div style="text-align:center">
<asp:Button ID="cmdConvert" runat="server" Text="Convert to °F" CssClass="btn"
OnClientClick="MyConvert();return false"/>
</div>
<br />
<label style="font-size:large">Fahrenheit</label>
<asp:TextBox ID="txtF" runat="server" style="font-size:large;margin-left:5px;text-align:center"
Width="80px" Wrap="false"
ClientIDMode="Static">
</asp:TextBox>
</div>
<script>
function MyConvert() {
var txtC = $("#txtC");
var txtF = $("#txtF");
$.ajax({
type: "POST",
url: "Autocom.aspx/ConvertToC",
data: JSON.stringify({ MyC: txtC.val()}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (MyReturn) {
txtF.val(MyReturn.d);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage)
}
});
}
I'm also a bit lazy, so I used clientID mode = static, as that makes the jQuery selector nice and easy to type in.
So, when we run the above, we get this result:
so, now your "mess".
it not particular what you goal here is with your sample.
(going for coffee, but study, and try the above).
Edit: Try this sample code
Your c# method in the page:
[WebMethod]
public static string SyncData(string data)
{
string sResult = "";
if (data != "")
{
if (data == "Yes")
{
sResult = "SyncDataYes";
}
else if (data == "No")
{
sResult = "SyncDataNo";
}
else
{
sResult = "SyncDataOther";
}
}
return sResult;
}
And your markup is this:
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server"
Checked="true" GroupName="G"
onclick="MyBtnClick('Yes')"
ClientIDMode="Static"
/>
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server"
GroupName="G"
onclick="MyBtnClick('No')"
ClientIDMode="Static"
/>
<br />
<h3>Result</h3>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<script>
function MyBtnClick(sYesNo) {
$.ajax({
type: "POST",
url: "TestAjax.aspx/SyncData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({data : sYesNo }),
success: function (MyResult) {
$('#TextBox1').val(MyResult.d);
},
failure: function (MyResult) {
alert('error');
}
});
}
</script>
Since ASP run at server control's ID will be generated different ID in client side, so these 2 event handlers binding will not work.
$('#RadioButtonYes').click(function () {...}
$('#RadioButtonNo').click(function () {...}
You could try 2 solutions:
Using control's ClientID for event binding
$('#<%=RadioButtonYes.ClientID%>').click(function () {...}
$('#<%=RadioButtonYes.ClientID%>').click(function () {...}
Adding ClientIDMode="Static" attribute to ASP control
<asp:RadioButton ID="RadioButtonYes" Text="Yes" runat="server" ClientIDMode="Static" Checked="true" GroupName="G" />
<asp:RadioButton ID="RadioButtonNo" Text="No" runat="server" ClientIDMode="Static" GroupName="G" />
** UPDATE:**
Your code also has two more problems:
1 - DataType of your ajax request (json) does not match with response type from server code (text/plain). You could check demo of not matching dataType of ajax request here: https://jsfiddle.net/p2yzLqu1/3/
2 - You were using wrong ajax's callback function failure. We should use done (success) and fail (error) callback functions instead. Please check sample of using done and fail callback at above demo.

Map Control form Client Side to Server Side HTML ASP Visual studio 2010

I have some problem about Map control name from client side to server side in HTML in Client side I have control MyTextBox
<body>
<form id="form1" method="get" action="Example2.aspx" >
<div>
<input id="MyTextBox" type="text" />
</div>
</form>
</body>
and i user Jquery post data to server side
$.ajax({
url: "Defaul.aspx/Myfunction",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
// alert(objEmployee);
},
data: '{"ID":"' + ID + '","FirstName":"' + FirstName + '"}',
success: function (msg) {
alert(msg.d);
}
}); // $.ajax
In the server side I want to get control name is "MyTextBox", how can I get it?

Jquery autocomplete textbox in asp.net

I am trying to implement jquery autocomplete textbox in asp.net. But I am getting the error "Object doesn't support this property or method" though while coding I am getting 'autocomplete' function in intellisense. I have tried to use google api link as well in case my jquery files are not getting loaded correctly, but i am getting the same error. Following is my code:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="Scripts/jquery-1.11.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.js" type="text/javascript"></script>
<link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function () {
$("[id*=txtPCTrx]").autocomplete({
source: function (request, response) {
$.ajax({
url: "PCAdd.aspx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{'txt':'" + $('[id*=txtPCTrx]').val() + "'}", //json to represent argument
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function (result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
</script>
Apart from the above autocomplete function I have many other jquery functions which are working properly in the same page. Please help.

how to execute server side click event after jquery pop up messgae

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$("[id*=btnModalPopup]").live("click", function () {
$("#modal_dialog").dialog({
title: "jQuery Modal Dialog Popup",
buttons: {
ok: function () {
$(this).dialog('close');
__doPostBack('btnModalPopup', 'OnClick');
//document.getElementById("btnModalPopup").click();
}
},
modal: true
});
return false;
});
</script>
<body>
<form id="form1" runat="server">
<div id="modal_dialog" style="display: none">
This is a Modal Background popup
</div>
<asp:Button ID="btnModalPopup" runat="server" Text="Show Modal Popup" ClientIDMode="static" OnClick="btnModalPopup_Click" />
</form>
</body>
Above Code Shows J query popup Message.It Works fine. but after popup message i need to execute server Side Code
if i Remove Return False from the script it execute the server Side Code But Popup message disappears. It should execute After popup's OK button Click
Please help....
Server Side Method
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Client Side
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
//do
}
});
}
function OnSuccess(response) {
btnModalPopup_Click();
}
Call ASP.Net Page Method using jQuery AJAX Example
Add ClientIdMode='static' to your button, return false from your event handler and try this in your OK button callback
OK: function() {
$(this).dialog('close');
__doPostBack('btnModalPopup','OnClick');
}

Jquery .ajax async postback on C# UserControl

I'm working on adding a todo list to a project system and would like to have the todo creation trigger a async postback to update the database. I'd really like to host this in a usercontrol so I can drop the todo list onto a project page, task page or stand alone todo list page.
Here's what I have.
User Control "TodoList.ascx" which lives in the Controls directory.
The script that sits at the top of the UserControl. You can see where I started building jsonText to postback but when that didn't work I just tried posting back an empty data variable and removed the 'string[] items' variable from the AddTodo2 method.
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#divAddButton").click(function() {
var jsonText = JSON.stringify({ tdlId: 1, description: "test test test" });
//data: jsonText,
$.ajax({
type: "POST",
url: "TodoList.aspx/AddTodo2",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('retrieved');
$("#divAddButton").text(msg.d);
},
error: function() {
alert("error");
}
});
});
});</script>
The rest of the code on the ascx.
<div class="divTodoList">
<asp:PlaceHolder ID="phTodoListCreate" runat="server">
<div class="divTLDetail">
<div>Description</div>
<div><asp:TextBox ID="txtDescription" runat="server"></asp:TextBox></div>
<div>Active</div>
<div><asp:CheckBox ID="cbActive" runat="server" /></div>
<div>Access Level</div>
<div><asp:DropDownList ID="ddlAccessLevel" runat="server"></asp:DropDownList></div>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="phTodoListDisplayHeader" runat="server">
<div id="divTLHeader">
<asp:HyperLink ID="hlHeader" runat="server"></asp:HyperLink>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="phTodoListItems" runat="server">
<div class="divTLItems>
<asp:Literal ID="litItems" runat="server"></asp:Literal>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="phAddTodo" runat="server">
<div class="divTLAddItem">
<div id="divAddButton">Add Todo</div>
<div id="divAddText"><asp:TextBox ID="txtNewTodo" runat="server"></asp:TextBox></div>
</div>
</asp:PlaceHolder>
<asp:Label ID="lbTodoListId" runat="server" style="display:none;"></asp:Label></div>
To test the idea I created a /TodoList.aspx page that lives in the root directory.
<uc1:TodoList runat="server" ID="tdl1" TodoListId="1" ></uc1:TodoList>
The cs for the todolist.aspx
protected void Page_Load(object sender, EventArgs e)
{
SecurityManager sm = new SecurityManager();
sm.MemberLevelAccessCheck(MemberLevelKey.AreaAdmin);
}
public static string AddTodo2()
{
return "yea!";
}
My hope is that I can have a control that can be used to display multiple todo lists and create a brand new todo list as well.
When I click on the #divAddButton I can watch it build the postback in firebug but once it completes it runs the error portion by alerting 'error'. I can't see why.
I'd really rather have the response method live inside the user control as well. Since I'll be dropping it on several pages to keep from having to go put a method on each individual page.
Any help would be appreciated.
I wasn't able to get the jquery ajax to work so I backed up and tried just putting the div and the jquery on the page itself and created a webservice.asmx page to handle the postbacks.
I'm still getting the error returned from the jquery and wondering if I've got something configured wrong or some other issue.
Here's the todo.aspx
<asp:Content runat="server" ContentPlaceHolderID="cpHolder" ID="ContentId">
<div id="divAddButton">Add Todo</div>
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#divAddButton").click(function() {
var jsonText = JSON.stringify({ Todo: { TodoId: 1, Description: "test test test"} });
//var jsonTextEmpty = jsonText.stringify({""});
$.ajax({
type: "POST",
url: "WebService.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('retrieved');
$("#divAddButton").text(msg);
},
error: function() {
alert("error");
}
});
});
});
The webservice.asmx is unchanged from the default bit Visual Studio created. Is there a way to find out what is causing the error?
In order to do this with jQuery as you describe, you need to sent it to a decorated method in your ASPX.cs file, you cannot send directly to the .ascx method. The good news is that the aspx.cs method can call the ascx one, so it is really pretty easy and you can just use it as a pass through to that.
[WebMethod]
public static string AddTodo2(myTodo todo2add)
{
//call your ascx method here
mymethod(todo2add.td1Id,todo2add.description);
return "yea!";
}
at the end of the aspx.cs, or in another class library put in your class so it knows how to decode the stuff:
public class myTodo
{
/// <summary>
/// web service/webmethod needs 0 parameter constructor
/// </summary>
public myTodo()
{
}
public myTodo(int tdlId, string description)
{
TdlId= tdlId;
Description= description;
}
public int TdlId;
public string Description;
}
slight change to the ajax call:
$("#divAddButton").click(function() {
var jsonText = JSON.stringify({myTodo:{ tdlId: 1, description: "test test test" }});
$.ajax({
type: "POST",
url: "TodoList.aspx/AddTodo2",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('retrieved');
$("#divAddButton").text(msg.d);
},
error: function() {
alert("error");
}
});
});

Categories