Get ServerDateTime from client side - javascript

I Have a javascript client side function to set the DateTime function.
function SetDateTime()
{
var presentDate = new Date();
}
Instead I like to get the date from server side whenever SetDateTime() function is called.
in .cs I have this method to return server time.
[System.Web.Services.WebMethod]
protected static string GetCurrentTime()
{
HiddenField hdnCurrentDateTime = new HiddenField();
hdnCurrentDateTime.Value = DateTime.Now.ToString();
return hdnCurrentDateTime.Value;
}
How to access this method from client side javascript? Thank you for your time.

using ajax call we can call webmethod like this
$.ajax({
type: "Post",
url: "pagename/GetCurrentTime",
contentType: "application/json",
dataType: "json",
success: function (data) {
alert(data);
}
}
});

As your method is static and assuming you have hdDate in your page, try this:
<asp:HiddenField ID="hdDate" runat="server"
value="<%# YourClassName.GetCurrentTime()%>" />

Related

On button click send Ajax call and get value from aspx.cs(code behind) to aspx page and display it in input field in the same page

I am new to AJAX and have stuck in a problem, I want to send AJAX CALL on button click, while button clicking the value of input field is sent to aspx.cs (code behind) page and response should be get and I try to show that response to that same input field but it's not working.
ASPX CODE:
<input type="text" class="wpcf7-text" id="d_id" name="d_id" runat="server"> // this id is sent to the Read_Driver_Account funtion and on response it is sending the driver cell number which i want to display in the driver cell number imput field
<input class="wpcf7-text" id="driver_cell" name="driver_cell" runat="server">
<asp:Button ID="btnn1" OnClick="Read_Driver_Account" runat="server" Text="Get"/>
<script>
$("btnn1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/Udate_Driver_Account/", //Udate_Driver_Account.aspx file is placed in VisualStudio/Websites/Fp/Udate_Driver_Account.aspx, where Fp is name of my website.
data: {
id: $(this).val(),
driver_cell: $("#drivercel").val()
},
success: function (result) {
alert('ok');
},
error: function (result) {
alert('error');
}
});
});
</script>
ASPX.CS CODE:
public string drivercel;
protected void Read_Driver_Account(object sender, EventArgs e)
{
var alldata = d_id.Value;
string driveradres = tokens[7];
string drivercel = tokens[8]; // i want to set this value to the input field id="driver_cell"
}
Note: tokens[8] is a value coming from a live database it's not a static value;
Also i want to set more than one values to more than one input fields.
The JQuery selector you used should be $("#btnn1") instead of $("btnn1"). Then the ajax url should be /pageName/webMethod like /Udate_Driver_Account.aspx/Read_Driver_Account.
And use JSON.stringify to send the data as data: JSON.stringify({ id: $(this).val(), driver_cell: $("#drivercel").val() }).
Add contentType: "application/json; charset=utf-8" to send the data as json and dataType: "json" to get the response data as json.
<input class="wpcf7-text" id="driver_cell" name="driver_cell" runat="server">
<asp:Button ID="btnn1" OnClick="Read_Driver_Account" runat="server" Text="Get"/>
<script>
$("#btnn1").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/Udate_Driver_Account.aspx/Read_Driver_Account", //Udate_Driver_Account.aspx file is placed in VisualStudio/Websites/Fp/Udate_Driver_Account.aspx, where Fp is name of my website.
data: JSON.stringify({
id: $(this).val(),
driver_cell: $("#drivercel").val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result);
// $("#drivercel").val(result.d);
},
error: function (result) {
alert('error');
}
});
});
</script>
Then mark your method with WebMethod attribute and make it as public static with parameter name same as the data json above.
public string drivercel;
[System.Web.Services.WebMethod]
public static string Read_Driver_Account(string id, string driver_cell)
{
string drivercel = tokens[8]; // i want to set this value to the input field id="driver_cell"
return drivercel;
}
Note: As you used the asp:Button id directly in JQuery selector, you should add ClientIDMode="Static" property to the button as below to use the same id in client side (OR add the same in Page directive). Otherwise, the button will have different dynamic id in client side and the JQuery click event won't get fired.
<asp:Button ID="btnn1" ClientIDMode="Static" OnClick="Read_Driver_Account" runat="server" Text="Get"/>

ajax script alert jquery

I create static web method and then i try to call this into script like this
UPDATE SCRIPT
<script type="text/javascript">
debugger;
alert("1");
$(function () {
$.ajax({
type: "GET",
url: "Maintenance.aspx/data_call",
//data: "",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("12");
debugger;
var re = JSON.parse(result.d).response;
debugger;
console.log(JSON.parse(result.d).response);
debugger;
},
error: function (error) {
alert(Error);
}
});
});
</script>
UPDATE
code
[WebMethod]
public static string data_call()
{
string result="";
Data td=new Data();
List<spselect_data_Result> selectdata=td.spselect_data().ToList();
DataTable dt=new DataTable();
dt.Columns.Add("RegionID",typeof(int));
dt.Columns.Add("Region",typeof(string));
dt.Columns.Add("StartDate",typeof(DateTime));
dt.Columns.Add("EndDate",typeof(DateTime));
foreach(var add in selectdata)
{
dt.Rows.Add(add.RegionID,add.Region,add.StartDate,add.EndDate);
}
result=DataSetToJSON(dt);
return result;
}
public static string DataSetToJSON(DataTable dt)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
// dict.Add(dt.TableName, arr);
dict.Add("response", arr);
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
}
protected void Page_Load(object sender, EventArgs e)
{
// data();
}
when i debug code then an alert show like this
function Error (){[native code]}
and when when i set debugger on jquery and check then debugger comes on alert 1 and then on this line $(function() { then after this directly execute on this line means ajax not call
first i try to display data on console
error on console
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
When I try this the call only shows alert("1"). alert("12") is not called. Where is the problem?
This problem maybe caused by maxJsonLength property in web.config file. To solve the problem You can chnage the MaxJsonLength property on your web.config:
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
The MaxJsonLength property is an integer property that by default set to 102400(100k) and cannot be unlimited.
I see some problems in the code you posted.
First of all you don't need type: "POST" as you are not posting/sending any data.
So update that portion in ajax request.
$(function() {
$.ajax({
type: "GET",
url: "Maintenance.aspx/YourMethod",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
alert("12");
debugger;
},
error: function (error) {
alert(Error);
}
});
});
Or else to work it with post you will have to set
data: "{}",
See instead of setting cache:false in ajax request set it from a common place like
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
Next on server side no need to call the method data in page load.
Just write it directly in class outside page load.And add the attribute WebMethod from System.web.services.
[WebMethod]
public static string YourMethod()
{
return "whatever you want";
}
Note : Also another thing I noticed that you made your method name as data,so my advice is change it to something meaningful as data is a ajax call parameter key and it could conflict.

How to pass a string from javascript to server? and then get a return value from server in asp.net webforms

I have this modal. inside a form tag
<div id="Incoming_Call" class="modal fade" role="document">
<asp:Label runat="server" id="Caller_id" Text="Incoming Call"</asp:Label>
</div>
I want to change the label text when the modal will show
<script>
string id = "temporary value"//javascript has this value on clientside.
// i don't have this value on page load but after some event triggers.
$('#Incoming_call').on('shown', function(){
id="zetawars#hotmail.com";
var text = '<%= generatestring(id)%>';
$('#<%=Caller_id.ClientID%>').html = id;
});
</script>
I need to send that id variable to server side to a function generateString() after the string has changed from id="temporary Value" to id="zetwars#hotmail.com" or something
This is on server side.
public string generateString(string id)
{
id = // does some processing;
return id;
}
So, I want to send a variable of javascript to the server side then server has to do some processing and return the value. the javascript variable is not ready at page load time. So I can't pass it inside <%%> these tags and get a newer value. It will only pass "temporary value" as a string not the new value.
Calling a server side method from javascript is really simple.You can do this with jQuery $.ajax function and a [WebMethod]
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string generateString(string id)
{
System.Diagnostics.Debugger.Break();
return String.Format("Response from server for - {0}.Call time - {1}",id,DateTime.Now.ToString("HH:mm:ss"));
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var id = "temporary value";
$("#btnMakeAjaxCall").click(function () {
MakeAjaxCall();
});
function MakeAjaxCall() {
$.ajax({
type: "POST",
url: "AjaxCallExample.aspx/generateString",
contentType: "application/json;charset=utf-8",
data: '{id:"' + id + '"}',
dataType: "json",
success: function (data) {
var caller = '<%: Caller_id.ClientID %>';
$("#" + caller).text(data.d)
},
error: function (errordata) {
console.log(errordata);
}
});
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" id="btnMakeAjaxCall" value="Make AJAX call" />
<asp:Label ID="Caller_id" runat="server" Text="Incoming Call"></asp:Label>
</form>
</body>
You can make an ajax call to server and use the returned value.
you can make ajax call each time the modal is shown
or
you can make ajax call whenever you are ready to get result from server, this way you can make ajax call and store the result in a hidden variable on page or some other already defined variable and use the variable in modal.
jQuery code to make ajax call to server
To make ajax call you need to add reference to jQuery in your page.
$.ajax({
url: "/controller_name/method_name",
type: "POST",
data: { var1:var1},
success: function (response) {
//use response here
},
error: function () {
alert("Some unexpected error occured. Please try again.");
}
});
This is the way you can accomplish what you want, lets us know id you need help in coding also.

Converting a Webform application to MVC

I am converting an ASP.NET WebForm application into an ASP.NET MVC application and being new to MVC, I am trying to make sure I do this right.
Currently, in my WebForm application, it is AJAX powered using jQuery and doing calls to WebMethods in the C# code behind. Currently, how the WebForm works now is there might a page with a few fields that need to be filled out and saved to the database. To do this, we'd have an HTML form and a save button. When the button is pressed, this javascript function is called:
function SaveForm()
{
if (!ValidateForm())
return;
ShowWaitingOverlay();
var params = {};
params.firstName = $('#<%= txtFirstName.ClientID %>').val();
params.lastName = $('#<%= txtLastName.ClientID %>').val();
params.address1 = $('#<%= txtAddress1.ClientID %>').val();
params.address2 = $('#<%= txtAddress2.ClientID %>').val();
// ... many more just like above
$.ajax({
type: "POST",
url: "Hosts.aspx/SaveHost",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
HideWaitingOverlay();
if (msg.d == "0") {
alert("Save Failed!");
}
}
});
}
This function would do an AJAX call to an ASP.NET Web Method that might look similar to this:
[WebMethod]
public static string SaveForm(string firstName, string lastName, string address1, string address2)
{
var host = new BusinessLayer.HostApplication();
host.FirstName = firstName;
host.LastName = lastName;
host.Address1 = address1;
host.Address2 = address2;
host.Save();
return host.HostId.ToString();
}
Of course there are other irrelevant details omitted for brevity, but this is the general idea.
My question is, what would be the correct "MVC way" of converting this? I would think a lot of this code would go away and/or be hidden in the data model. I wouldn't think it would be necessary to have to need all the lines that assign each individual textbox/dropdown, etc to the params variable.
You could have an action method that get a DTO object and returns a Json result. In this action method, you could call the business layer to proceed the flow. For sample:
[HttpPost]
public ActionResult SaveForm(CustomerDTO input)
{
var host = new BusinessLayer.HostApplication();
host.FirstName = input.FirstName;
// oth properties
host.Save();
return Json(new {success = host.HostId != 0});
}
and your DTO could be:
public class CustomerDTO
{
public string FirstName { get; set; }
// other properties
}
In the client-side, you could try this:
$.ajax({
type: "POST",
url: "#Url.Action("SaveForm", "ControllerName")",
data: $("#formId").serialize(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
if (result.success)
{
HideWaitingOverlay();
}
else
{
alert("Save Failed!");
}
}
});

ASP.Net call codebehind on $.ajax success

I have a page (default.aspx) with codebehind. The a$.ajax url is getting a response from one place, and on its success I want to call the codebehind function.
(In case I made a mistake while obfuscating the code, the $.ajax works perfectly and I get the desired response).
How is this possible?
Code I'm using:
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
$.ajax({
type: "POST",
url: URL,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var resultCount = response.d
alert("*** RESULT ****" + resultFields);;
var string = StringReturn(); // the codebehind
alert(string);
},
error: function (e) {
alert("Unavailable");
}
});
Codebehind:
[WebMethod]
protected static string StringReturn()
{
return "StringReturn() success";
}
However, I'm getting error messages saying that StringReturn isn't a valid function.
Any help would be appreciated?
I've added the following lines of code to the page as advised:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
I've also changed the code to call a javascript function on the Success event, the function being:
function HelloWorlds() {
alert("HelloWorld() method");
message = PageMethods.StringReturn();
message.toString();
alert(message);
}
however that doesn't appear to work. What am I missing?
You need to have a scripmanager on your page and then you can call it like this PageMethods.StringReturn()

Categories

Resources