I study javascript. Got to ajax requests. Everything works fine in mvc. I decided to try on web forms. Trying to post a new entry on the page, please tell me what I'm doing wrong. Here is my code. The page code acts as the main view:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Tables.aspx.cs" Inherits="WebApplication1.Tables" %>
<!DOCTYPE html>
<script src="../../Scripts/jquery-1.8.0.min.js"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js"></script>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<div>
<table id="tab" class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Author</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1408</td>
<td>Stiven King</td>
<td>500</td>
</tr>
</tbody>
</table>
</div>
<form id="form1" runat="server">
<asp:TextBox ID="txbName" runat="server"></asp:TextBox>
<asp:TextBox ID="txbAuthor" runat="server"></asp:TextBox>
<asp:TextBox ID="txbPrice" runat="server"></asp:TextBox>
<input id="btnAdd" type="submit" value="Добавить" />
</form>
</body>
</html>
<script>
$('#btnAdd').on('click', function () {
$.ajax({
type: "POST",
url: "Tables.aspx/AddBook",
data: JSON.stringify({
"Name": $('#txbName').val(),
"Author": $('#txbAuthor').val(),
"Price": $('#txbPrice').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (MyDT) {
$('#tab tbody').append(MyDT);
},
error: function (xhr) {
alert(xhr.statusCode)
}
});
});
</script>
Web method code, controller:
[WebMethod]
public static string AddBook(string Name, string Author, int Price)
{
db = new Context();
string html = "";
Book book = new Book() { Name = Name, Author = Author, Price = Price };
db.Books.Add(book);
db.SaveChanges();
html = GetHTMLRow(book);
return html;
}
And another method of obtaining html code for further adding an entry to the page, something like a partial view on which the entry is going to:
public static string GetHTMLRow(Book book)
{
string htmlRow = $"<tr><td>{book.Name}</td><td>{book.Author}</td><td>{book.Price}</td></tr>";
return htmlRow;
}
My code is completely working, but for some reason the page is restarted. But shouldn't ajax request work asynchronously without touching the page? In MVC everything works fine. And then why not? What can be wrong?
when you click the button it submits the form(because the type is set to "submit"). change it to "button"
<input id="btnAdd" type="button" value="Добавить" />
Related
I'm writing a C# project,
One of my needs is to expose button when TextBox (not dynamic) have more then 1 letter, As long as i know changes (which includes functions activation) will happen only between postacks.
Is there any possibilty to check the Texbox letter content without using postback (Includes skip on page load function).
Thanks Ahead.
Is there any possibilty to check the Textbox letter content without
using postback (Includes skip on page load function).
Assuming you are using ASP.NET Web Form, you could call WebMethod via Ajax.
After posting back to server via Ajax,
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox runat="server" ID="TextBox1" />
<button type="button" onclick="postData();">Post Data</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
function postData() {
var data = { text: $('#<%= TextBox1.ClientID %>').val() };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postdata") %>',
data: JSON.stringify(data),
contentType: 'application/json',
success: function (msg) {
$('#<%= TextBox1.ClientID %>').val(msg.d);
}
});
}
</script>
</form>
</body>
</html>
Code Behind
using System;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostData(string text)
{
return text + DateTime.Now;
}
}
}
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1
-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Login Page</title>
<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="wholeContent">
<div id="login">
<table border="2">
<tr>
<td>
User Id
</td>
<td>
<input type="text" id="txtId" name="txtId" />
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<input type="text" id="txtPwd" name="idPwd" />
</td>
</tr>
<tr>
<td>
<input type="button" id="btnSubmit" value="Login" />
</td>
</tr>
</table>
</div>
<div id="success">
</div>
<div id="error">
</div>
</div>
<script type="text/javascript">
$(document).ready(function()
{
$("#btnSubmit").click(function()
{
var uid = $("#txtId").val();
var pwd = $("#txtPwd").val();
var data=JSON.stringify({uid:uid,pwd:pwd});
$.ajax({
type: "POST",
url: "Default.aspx/ValidationWebMethod",
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",
// data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
success: function (data)
{
alert(" Successful Login "+data.d);
// location.reload();
},
error: function(resp,textStatus,errorThrown)
{
alert("error : " + errorThrown + " || Check your Id and Password || "+ resp.d);
}
});
});
});
</script>
</form>
</body>
</html>
This is my code-behind (part of the code)
[System.Web.Services.WebMethod]
public static void ValidationWebMethod(string uid, string pwd)
{
string text = uid + " : " + pwd;
System.IO.File.WriteAllText(#"D:\TrackLog.txt", text);
string[] flags = new string[1];
// bool valid = true;
if (uid.Equals("arijit") && pwd.Equals("admin"))
{
flags[0] = "true";
// return flags;
}
else
{
flags[0]="false";
// return flags;
}
}
Now when I am clicking the button (btnSubmit) its giving syntax error:Invalid Character (the errorThrown variable here in the alert box)..Please can you tell me why is it happening?
The problem is here
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",
As you changed the data in json format with JSON.stringify
var strdata=JSON.stringify({uid:uid,pwd:pwd});
So you no need to pass data to ajax method like you do above.
Try this
data: strdata // renamed variable
instead of
data: "{ 'uid': '" + uid + "','pwd': '"+pwd+"'}",
Your ValidationWebMethod does not return anything. Make it return, for example, string.
First, I want to let everyone know that I am using an aspx engine not a Razor engine.
I have a table within a form. One of my textbox contains html tags like
</br>Phone: </br> 814-888-9999 </br> Email: </br> aaa#gmail.com.
When I go to build it it it gives me an error that says:
A potentially dangerous Request.Form value was detected from the client (QuestionAnswer="...ics Phone:<br/>814-888-9999<br...").
I tried the validation request="false" but it did not work.
I am sorry I didn't add my html code for you to look at so far. I am pulling some question up where I can edit it, if need be.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
EditFreqQuestionsUser
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$("#freqQuestionsUserUpdateButton").click(function () {
$("#updateFreqQuestionsUser").submit();
});
});
</script>
<h2>Edit Freq Questions User </h2>
<%Administrator.AdminProductionServices.FreqQuestionsUser freqQuestionsUser = ViewBag.freqQuestionsUser != null ? ViewBag.freqQuestionsUser : new Administrator.AdminProductionServices.FreqQuestionsUser(); %>
<%List<string> UserRoleList = Session["UserRoles"] != null ? (List<string>)Session["UserRoles"] : new List<string>(); %>
<form id="updateFreqQuestionsUser" action="<%=Url.Action("SaveFreqQuestionsUser","Prod")%>" method="post" onsubmit+>
<table>
<tr>
<td colspan="3" class="tableHeader">Freq Questions User Details <input type ="hidden" value="<%=freqQuestionsUser.freqQuestionsUserId%>" name="freqQuestionsUserId"/> </td>
</tr>
<tr>
<td colspan="2" class="label">Question Description:</td>
<td class="content">
<input type="text" maxlength="2000" name="QuestionDescription" value=" <%=freqQuestionsUser.questionDescription%>" />
</td>
</tr>
<tr>
<td colspan="2" class="label">QuestionAnswer:</td>
<td class="content">
<input type="text" maxlength="2000" name="QuestionAnswer" value="<%=freqQuestionsUser.questionAnswer%>" />
</td>
</tr>
<tr>
<td colspan="3" class="tableFooter">
<br />
<a id="freqQuestionsUserUpdateButton" href="#" class="regularButton">Save</a>
Cancel
</td>
</tr>
</table>
</form>
</asp:Content>
before the page is submitted you need to html encode the textbox's value, with window.escape(...)
If you need the un-escaped text on the server side then use HttpUtility.UrlDecode(...) method.
very quick sample:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SO.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function makeSafe() {
document.getElementById('TextBox1').value = window.escape(document.getElementById('TextBox1').value);
};
function makeDangerous() {
document.getElementById('TextBox1').value = window.unescape(document.getElementById('TextBox1').value);
}
</script>
</head>
<body>
<form id="form1" runat="server" onsubmit="makeSafe();">
<div>
<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Rows="10" ClientIDMode="Static"></asp:TextBox>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
<script>
makeDangerous();
</script>
</body>
</html>
Make these changes to your code:
<script type="text/javascript">
$(document).ready(function () {
makeDangerous();
$("#freqQuestionsUserUpdateButton").click(function () {
makeSafe();
$("#updateFreqQuestionsUser").submit();
});
});
// Adding an ID attribute to the inputs you want to validate is simplest
// Better would be to use document.getElementsByTagName and filter the array on NAME
// or use a JQUERY select....
function makeSafe() {
document.getElementById('QuestionAnswer').value = window.escape(document.getElementById('QuestionAnswer').value);
};
// In this case adding the HTML back to a textbox should be 'safe'
// You should be very wary though when you use it as actual HTML
// You MUST take steps to ensure the HTML is safe.
function makeDangerous() {
document.getElementById('QuestionAnswer').value = window.unescape(document.getElementById('QuestionAnswer').value);
}
</script>
Decorate your controller action with the [ValidateInput] attribute:
[ValidateInput(false)]
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
...
}
Client JavaScript:
function codificarTags()
{
document.getElementById('txtDescripcion').value = document.getElementById('txtDescripcion').value.replace(/</g,'<').replace(/>/g,'>');
}
<form id="form1" runat="server" onsubmit="codificarTags();">
Server:
protected void Page_Load(object sender, EventArgs e)
{
txtDescripcion.Text = txtDescripcion.Text.Replace(#"<", #"<").Replace(#">", #">");
}
I would suggest using the AjaxControlToolkit's HTML Editor. I'm implementing that now. If you're textbox is multi-line and big enough to accommodate HTML, why not just bump it up to an HTML editor. Your user will be happier too.
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/HTMLEditor/HTMLEditor.aspx
Using html in textbox is not a good practice, maybe use linebreaks (Environment.NewLine) or \r\n instead of br ?
.NET Reference
Example (in C#) :
textBox1.Multiline = true;
textBox1.Text = "test" + Environment.NewLine + "test2";
I took a bit of a different approach. I wanted to use html textboxes widely across my application. I made a user control which would avoid editing the javascript every time I added a new control. My entire control is very custom but the heart of the html handling is as seen below.
The UserControl markup has some simple javascript to escape and unescape the textbox.
<script type="text/javascript">
function UnescapeControl(clientId) {
$('#' + clientId).val(window.unescape($('#' + clientId).val()));
}
function EscapeAllControls() {
var escapeControList = JSON.parse('<%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(EscapeControlList) %>');
for (var i = 0; i < escapeControList.length; i++)
EscapeControl(escapeControList[i]);
}
function EscapeControl(textClientId) {
document.getElementById(textClientId).value = window.escape(document.getElementById(textClientId).value);
}
</script>
<asp:TextBox ID="Txt_SavableText" CssClass="form-control" Width="100%" runat="server" ></asp:TextBox>
The code behind is responsible for escaping the controls before the post back using RegisterOnSubmitStatement and unescaping them using RegisterStartupScript after the post back.
public partial class SavableTextBox : System.Web.UI.UserControl
{
public List<string> EscapeControlList
{
get
{
if (Session["STB_EscapeControlList"] == null)
Session["STB_EscapeControlList"] = new List<string>();
return (List<string>)Session["STB_EscapeControlList"];
}
set { Session["STB_EscapeControlList"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (EscapeHtmlOnPostback && !EscapeControlList.Contains(GetClientId()))
EscapeControlList.Add(GetClientId());
// When using a script manager, you should use ScriptManager instead of ClientScript.
if (EscapeHtmlOnPostback)
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "UnescapeControl_" + GetClientId(), "UnescapeControl('" + GetClientId() + "');", true);
// Ensure we have our escape script called before all post backs containing escapable controls.
// This is like calling OnClientClick before everything.
if (EscapeControlList != null && EscapeControlList.Count > 0)
this.Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "SaveableTextBoxEscaper", "EscapeAllControls();");
}
public string Text
{
get
{
return Txt_SavableText.Text;
}
set
{
Txt_SavableText.Text = value;
}
}
public string GetClientId()
{
return Txt_SavableText.ClientID;
}
}
Now we can use it anywhere like this while setting EscapeHtmlOnPostback="True".
<%# Register TagPrefix="STB" TagName="SavableTextBox" Src="~/SavableTextBox.ascx" %>
<STB:SavableTextBox ID="Txt_HtmlTextBox" EscapeHtmlOnPostback="True" runat="server" />
Note, when we access Txt_HtmlTextBox.Text during the post back it will already be escaped for us.
I have to fix a bug on a website that is using asp.net and i don't know much about it (asp.net c# mvc)...
the problem is in a plugin named uploadify, and it calls for the script to upload files:
'script': '<%= ResolveUrl("~/Build/UploadImages")%>/<%= ViewData["build_id"] %>',
in the browser show like this:
'script': '/prod/cms/Build/UploadImages/680ad442-8e9c-459c-b253-e9c389c1622b',
the problem is that the folder 'Build' doens't exist, i think it's created by asp.net....
I can't find the code that uploads the file... I searched everywhere with the words 'SaveAs', 'SaveFileAs', 'Upload', 'Uploadify' in all files, and i still haven't found it yet...
the problem that uploadify gives is 'HTTP Error' after it show 100% of upload, I searched on google but no luck... i think if i found the script that uploads the file, maybe i can fix it
here's the all script of my file:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Framework.Models.Image>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Photo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Photo</h2>
<p>
<label>
Tipo:</label>
<%= Html.DropDownList("type", (SelectList)ViewData["types"], new { onchange = "changeScript(this.value)" })%>
</p>
<div id="dvUpload">
<input id="upload" name="upload" type="file" />
Fazer Upload | Limpar Uploads
</div>
<%-- <% using (Html.BeginForm("UploadImages", "build", new { id = ViewData["build_id"], type = "c1956908-64f5-4195-ba73-4d7710d560d7" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input id="File1" name="upload" type="file" />
<input type="submit" value="Enviar" />
<%} %>--%>
<br />
<br />
<table>
<tr>
<th>
</th>
<th>
Type
</th>
<th>
Imagem
</th>
<th>
Legenda
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%= Html.ActionLink("Apagar", "deleteimage", new { id = item.Properties.id, build_id = item.Properties.build_id }, new { onclick = "return confirm('Confirma esta ação?')" })%>
</td>
<td>
<%= Html.Encode(item.Type)%>
</td>
<td>
<img src="<%= Cms.Helpers.Settings.CMS_ADDRESS + item.Properties.url_address %>" width="150" height="100" />
</td>
<td>
<%= Html.TextBox(item.Properties.id.ToString(), item.Properties.description) %>
<input type="button" value="Ok" onclick="saveLegend('<%= item.Properties.id.ToString() %>')" />
</td>
</tr>
<% } %>
</table>
<p>
<%= Html.ActionLink("Create New", "Create") %>
</p>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="HeaderContent" runat="server">
<script type="text/javascript" src="<%= ResolveUrl("~/Content/JS/swfobject.js") %>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Content/JS/jQuery/jquery.uploadify.v2.1.0.js") %>"></script>
<script type="text/javascript">
var html = "";
jQuery(document).ready(function() {
html = jQuery("#dvUpload").html();
jQuery("#upload").uploadify({
'uploader': '<%= ResolveUrl("~/Content/Flash/uploadfy.swf") %>',
'script': '<%= ResolveUrl("~/Build/UploadImages")%>/<%= ViewData["build_id"] %>',
'cancelImg': '<%= ResolveUrl("~/Content/Images/cancel.png") %>',
'folder': '<%= ResolveUrl("~/Content/Images") %>',
'multi': true,
'simUploadLimit': 10,
'fileDesc': 'Apenas Imagens são permitidas',
'fileExt': '*.gif;*.jpg;*.png',
'onError' : function(errorType) {
//alert('The error was ' + errorType.toSource());
alert(JSON.stringify(errorType, null, 4));
},
'onComplete': function() {
alert("foi tudo");
}
});
AddNullValueSelectObject('type');
});
function Upload(build_id) {
jQuery('#upload').uploadifyUpload();
}
function changeScript(val)
{
jQuery("#dvUpload").empty();
jQuery("#dvUpload").html(html);
var culture = jQuery('#culture').val();
jQuery("#upload").uploadify({
'uploader': '<%= ResolveUrl("~/Content/Flash/uploadfy.swf") %>',
'script': '<%= ResolveUrl("~/Build/UploadImages")%>/<%= ViewData["build_id"] %>?type=' + val,
'cancelImg': '<%= ResolveUrl("~/Content/Images/cancel.png") %>',
'folder': '<%= ResolveUrl("~/Content/Images") %>',
'multi': true,
'simUploadLimit': 10,
'fileDesc': 'Apenas Imagens são permitidas',
'fileExt': '*.gif;*.jpg;*.png',
'onError' : function(errorType) {
//alert('The error was: ' + errorType.toSource());
alert(JSON.stringify(errorType, null, 4));
},
'onComplete': function() {
alert("foi tudo");
}
});
}
function saveLegend(id)
{
var text = jQuery('#' + id).val();
jQuery.ajax({
type: 'GET',
url: '<%= ResolveUrl("~/build/UpdatePhotoLegend")%>/' + id,
data: 'legend=' + text,
success: function(data) {
alert('Alterado com sucesso!');
}
});
}
function AddNullValueSelectObject(object_id) {
jQuery('#' + object_id).append("<option value='00000000-0000-0000-0000-000000000000'>--- SELECIONE ---</option>");
jQuery("#" + object_id + " option[value='00000000-0000-0000-0000-000000000000']").attr('selected', 'selected');
}
</script>
</asp:Content>
thanks in advance...
Normally I wouldn't answer unless I was fairly sure of my answer, however, since noone else is responding...
I have no experience with uploadify but it looks like you are using an old version of uploadify and the api has changed quite a bit so it's hard for me to say for sure. I think the 'script' parameter is actually referring to the server side "script" that would normally handle the saving of the uploaded file (the 'uploader' parameter in the current version http://www.uploadify.com/documentation/uploadify/uploader/).
Do you have a BuildController class with an UploadImages action (method)? If so, that is probably one of the causes of your error (something erroring while saving to disk). If you do have a BuildController, I wonder if that call to resolve url is correct? The resolved path looks off to me (normally you would not resolve a route based url in mvc as resolve url isn't route aware).
If you don't have a BuildController and I'm totally off let me know and I'll remove this answer. It's somewhat a shot in the dark. But it is plausible.
EDIT: Just in case you have no experience in MVC at all, the code from the "Build folder" should be located in your mvc web app under a folder called Controllers inside a class called BuildController inside a Method called UploadImages.
Promoted my comment to an answer
It's possible that the script is embedded as a resource. Try using ILSpy to confirm this. In that case you will need to access the source code. Also, it maybe that the script was minified/obfuscated and that's why you can't find anything.
I am working with the C#, ASP.NET framework [very new to this environment]. This is what I want to achieve:
Pass data from jQuery Datepicker textbox to controller
Parse the date, database query from the selected range
Asynchronously, send queried rows back to page to update content
Here is the HTML:
<form id="date" runat="server">
<asp:Label AssociatedControlId="from_date" Text="From:" runat="server" />
<asp:TextBox ID="from_date" Text="" runat="server" />
<asp:Label AssociatedControlId="to_date" Text="To:" runat="server" />
<asp:TextBox ID="to_date" Text="" runat="server" />
</form>
I have this snippet on the client side to handle the change event:
var dates = $('#from_date, #to_date').datepicker({
if ( this.id == "to_date" )
$('#to_date').change();
});
To call in the controller:
protected void to_date_UpdateHandler( object sender, EventArgs e ) {
/* from here, I would query within the ranges in the "from_date"
and "to_date" textboxes */
}
Obviously, this will cause a page refresh, but I want to pass the data along asynchronously. How should I go about achieving this? Thank you.
It's a little unclear from your question which particular jQuery 'datepicker' plugin you are using, so I will proceed to use the jQuery UI date picker for this example.
First off, there are some things you should be aware of when working with jQuery and ASP.NET WebFroms. Specifically, up until very recently, when server controls are rendered, their IDs get mangled by .NET. It is usually a good idea to stick to CSS classes when doing lots of client side scripting, but if you must use IDs, you can select controls like so:
var $toDate = $('input[id$=to_date]');
Secondly, you will need to communicate with the server via WebMethods or by configuring an ASPX page to return XML or JSON. ASP.NET MVC really makes this easy, but it's possible in WebForms and definitely worth your time (I despise UpdatePanels).
Now to some code.
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Example ASP.NET/jQuery Datepicker</title>
<link type="text/css" rel="stylesheet" href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/themes/redmond/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js"></script>
<script type="text/javascript" src=" http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.js"></script>
<script type="text/javascript">
// On DOM ready...
$(function() {
// Cache the date pickers
var $fromPicker = $('.from_date'),
$toPicker = $('.to_date');
// Init the date pickers
$fromPicker.datepicker();
$toPicker.datepicker();
// Handle change event for 'to' date
$toPicker.change(function(e) {
// Get the dates
var fromDate = $fromPicker.datepicker('getDate');
var toDate = $(this).datepicker('getDate')
// prepare the data to be passed via JSON
var dates = {
fromDate: fromDate,
toDate: toDate
};
// Call the web method
$.ajax({
type: 'POST',
url: 'Default.aspx/GetDate',
data: $.toJSON(dates),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert(msg.d);
}
});
});
// Log errors
$(".log").ajaxError(function() {
$(this).text("Error in ajax call.");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<asp:Label ID="from_date_lbl" AssociatedControlID="from_date" Text="From:" runat="server" />
<asp:TextBox ID="from_date" CssClass="from_date" Text="" runat="server" />
<asp:Label ID="to_date_lbl" AssociatedControlID="to_date" Text="To:" runat="server" />
<asp:TextBox ID="to_date" CssClass="to_date" Text="" runat="server" />
<asp:Label ID="log_lbl" CssClass="log" runat="server" />
</form>
</body>
</html>
ASPX.CS
using System;
using System.Web.Services;
public partial class _Default : System.Web.UI.Page
{
[WebMethod]
public static string GetDate(string fromDate, string toDate)
{
DateTime dtFromDate;
DateTime dtToDate;
// Try to parse the dates
if (DateTime.TryParse(fromDate, out dtFromDate) &&
DateTime.TryParse(toDate, out dtToDate))
{
// Perform calculation and/or database query
return "success!";
}
return null;
}
}