<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');
}
Related
Hi i am having a problem inserting records into database. I am using entity framework as my back end. I have the following code. I am unable to figure out the actual problem in my code since showing no error message when try to run.
.aspx
<link rel="stylesheet" href="/Content/jquery-ui.css" type="text/css" />
<script type="text/javascript" src="/Scripts/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="/Scripts/1.8.24/jquery-ui.min.js"></script></script>
<script type="text/javascript">
function SaveRecord() {
//Get control's values
var Name = $.trim($('#<%=txtCompanyName.ClientID %>').val());
var msg = "";
//check for validation
if (Name == '') {
msg += "Please enter Name";
}
if (msg.length == 0) {
//Jquery Ajax call to server side method
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "company_master.aspx/InsertCompany",
data: "{'Name':'" + Name + "'}",
success: function (response) {
if (response.d == true) {
$('#lblMsg').text("Saved successfully");
//Clear/Reset controls
$('#txtCompanyName').val('');
//$('#ddlDeptId').val("0");
}
else {
$('#lblMsg').text("Not Saved");
}
},
error: function (xhr, textStatus, error) {
$('#lblMsg').text("Error: " + error);
}
});
}
else {
$('#lblMsg').html('');
$('#lblMsg').html(msg);
}
}
</script>
<div>
<asp:TextBox ID="txtCompanyName" runat="server" placeholder="Enter Company Name" ></asp:TextBox>
<asp:Label ID="lblMsg" runat="server"></asp:Label>
<button type="submit" onclick="SaveRecord()"/>Submit
</div>
C# Code Behind:
using System.Web.Services;
[WebMethod]
public static bool InsertCompany(string Name)
{
bool status = false;
try
{
var company = new CompanyMaster
{
CompanyName = Name
};
using (var context = new DBEntities())
{
context.CompanyMaster.Add(company);
context.SaveChanges();
}
status = true;
}
catch (Exception ex)
{
throw ex;
}
return status;
}
Kindly help me to overcome this problem. Thank you.
No problem your code. can you look in console of chrome?
Request returned 404 or 500.
You can check url :
url: "/company_master.aspx/InsertCompany",
Try this
<button type="button" onclick="SaveRecord(); return false">Submit</button>
Also, check in your browser console, if there's any other error
Try using <input type='button'> and see how that works. There may be a submission conflicting with the event that sends the AJAX request.
I copied your code, and it works without tweaking. The only difference is I have this
<form id="form1" runat="server">
and the div is contained within that. Use default browser as google chrome, and debug using chrome developer tools, it saves time.
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?
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.
I have some JavaScript code that will display a modal dialogue box asking the user to wait while it runs a web service that could take several seconds to run. What cannot figure out is how to launch the JS code from my C# code running in the server. Here is the scenario:
1) User clicks asp:Button code that launches server code.
2) Server code [somehow] fires a browser event that launches the JS code that calls the web service
The JS code looks like this:
<form id="form1" runat="server">
<div>
<script type="text/javascript">
$(function () {
$('#btn_BeginProcessB').click(function (event) {
event.preventDefault();
var $Seconds = $("INPUT[id*='txtSeconds']").val();
var $Message = $("INPUT[id*='txtMessage']").val();
var $WorkingMessage = $('#WorkingMessage');
$WorkingMessage.text($Message);
var $this = $(this);
var $Loader = $('#Loader');
// show loading indicator
$Loader.show();
$("body").css({ background: "#C8C5C5" });
// Begin process
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Seconds: $Seconds }),
url: 'SimpleWebService.asmx/LongRunningProcess',
error: function (xhr, textStatus, errorThrown) {
alert('Error! ' + errorThrown);
// show button
// hide loading indicator
$Loader.hide();
},
success: function (data) {
alert("Data:" + data.d);
// show button
// hide loading indicator
$Loader.hide();
$("body").css({ background: "#FFFFFF" });
}
});
});
});
</script>
<script type="text/javascript">
function LoadPageWorking() {
var $Seconds = $("INPUT[id*='txtSeconds']").val();
var $Message = $("INPUT[id*='txtMessage']").val();
var $WorkingMessage = $('#WorkingMessage');
$WorkingMessage.text($Message);
var $data = JSON.stringify({ Seconds: $Seconds });
PageWorking('Loader', 'SimpleWebService.asmx/LongRunningProcess', $data, PageWorkingSuccess, PageWorkingError);
};
function PageWorkingSuccess(data) {
$("SPAN[id*='lblResult']").html("<br /><b>Result:</b>" + data.d + "<br />");
$('body').css('background', originalBackground);
};
function PageWorkingError(xhr, textStatus, errorThrown) {
alert('Error! ' + errorThrown);
$('body').css('background', originalBackground);
}
</script>
<!--- HTML --->
<div id="Page">
<h1>
Long Running Process Test Page</h1>
<p>
This site demonstrates how to invoke a long running process and let the user know
that the process is underway. When the button is clicked, it calls a web service
that sleeps for the designated number of seconds and returns a message.</p>
<br />
Enter number of seconds for worker process to sleep:
<asp:TextBox ID="txtSeconds" runat="server" Width="25" Text="3" /><br />
Enter the message to be displayed while the process is working:
<asp:TextBox ID="txtMessage" runat="server" Text="Working...(please be patient)"
Width="300px" /><br />
<asp:Label ID="lblResult" runat="server" />
<br />
<input type="button" id="btnBegin" value="Click to test LoadPageWorking function"
onclick="LoadPageWorking();" />
</div>
<div id="Loader">
<center>
<span id="WorkingMessage">Default Loader Message</span>
<div class="ProgressBar-Animated">
</div>
</center>
</div>
</div>
</form>
What code can I write in my C# event that will fire the LoadPageWorking() JS function?
Even if you have a server side button control, you can use it's onclientclick property to call javascript directly. But if you have to call the script from code behind, you can use ClientScriptManager.RegisterStartupScript() or ClientScriptManager.RegisterClientScriptBlock() based on your requirement. There are plenty of examples out there.
Have the button trigger a page working function that creates some indicator that you are working, fire off the ajax request, and when it comes back finish the working and hide the indicator. No need to ever have to go to code behind.
Why don't you have your LoadPageWorking() start the server, then show the JS modal popup? You can have your popup poll your service to determine if it's completed, and hide itself when it is.
You should try using the RegisterClientScriptBlock method. It will allow you to dynamically add script sections to your page's source. You can include any Javascript you'd like, including invocation of a method already defined in the page.
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");
}
});
});