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;
}
}
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;
}
}
}
I want to get HTML DIV content via asp.net C# code behind event.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Report.aspx.cs" Inherits="WebApplication1.Report.Report" %>
<!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 src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#_Hidden_CrystalReportContent').hide();
$('#_Hidden_CrystalReportContent').html("<b>I want to get Current value. 1<sup>st</sup></b>");
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="_Hidden_CrystalReportContent">I want to get Current value.</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</body>
</html>
My code behind file as below.
public partial class Report : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{}
protected void Button1_Click(object sender, EventArgs e)
{
string s = Request["_Hidden_CrystalReportContent"].ToString();
}
}
But I still cannot get div content value.
Please let me get your suggestion.
Make the div runat="server" to access on server.
Html
<div id="_Hidden_CrystalReportContent" runat="server">
Code behind
string htmlOfDiv = _Hidden_CrystalReportContent.innerHTML;
Javascript
$(document).ready(function () {
$('#<% _Hidden_CrystalReportContent.ClientID %>').hide();
$('#<%= _Hidden_CrystalReportContent.ClientID %>').html("<b>I want to get Current value. 1<sup>st</sup></b>");
});
Making a div server accessible by puttin runat="server" attribute cause the changed client id if CLientIDMode is not static. You will need to use ClientID attribute to get client id of div in javascript.
Edit: based on comments. You are trying to get the updated html, if so you then you wont get it as on post back only html form elements are posted. Put the changes in some hidden field and assess it on server.
In html
<input type="hidden" id="hdnDivContents" runat="server">
In javascript
$('#<% hdnDivContents.ClientID %>').val("<b>I want to get Current value. 1<sup>st</sup></b>");
In code behind
_Hidden_CrystalReportContent.innerHTML = hdnDivContents.Value;
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 am trying to modify a simply chat application for learning purposes. The only change i made was to change a button to a serverside control. The problem i have is that the first time i broadcast a message, it works, and the Clients.addNotification(msg) is called. Yet the second time, although the javascript works, at its final step, the javascript undos all the changes and the Clients.addNotification(..) is never called :/ It only works for the first time! I have to rebuild my project to see it working again (a page refresh won't work)
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.addNotification(message);
}
}
My aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Client1.aspx.cs" Inherits="WebApplication1.WorkingWithHubs.Client1" %>
<!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 src="../Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="../Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addNotification = function (message) {
$('#messages').append('<li>' + message + '</li>');
var labelValue = $('#total').val();
$('#total').val(parseInt(labelValue, 10) + 1);
};
$("#btn").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server" />
<div>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<input type="text" id="msg" runat="server" />
<asp:Button ID="btn" runat="server" Text="BroadCast" OnClick="btn_click" ClientIDMode="static" />
<input type="text" id="total" value="0" />
<ul id="messages">
</ul>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
My code behind:
public partial class Client1 : System.Web.UI.Page
{
public List<String> list = new List<String>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_click(object sender, EventArgs e)
{
list.Add(msg.Value);
}
}
Once this example work I will shift the code to another application I am working on so that notifications can be immediately pushed to all clients.
I am a very beginner and I would appreciate all your help! Thanks a lot guys!
EDIT:
when checking out the network tab (on my chrome), for the first click I get a 'send' (signalR) and Client1.aspx and all works fine, for the second click onwards, I only get Client1.aspx, and no send whatsoever :/
for a quick and dirty solution, just place the update panel ONLY around the button, and remove
$("#btn").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
and instead, insert the following in the beginning
$('#form1').delegate('#btn', 'click', function () {
chat.send($('#msg').val());
});
Thanks to my friends shifty and red_square :)
Is there a way to send data to an aspcontrol say a label called label1? Via jquery?
I know jquery only likes html but is there a way to just send the raw text to an asp control using a similar method below:
<script type="text/javascript">
$(function () {
$('button').click(function () {
$(document).ready(function () {
var x = $('textarea').val();
$('textarea').val('');
var label = $("#<%= Label1.ClientID %>");
var newdiv = $("<div></div>").html(x).attr('id', 'test');
$('#test1').append(newdiv);
var serializer = new XMLSerializer();
label.text(serializer.serializeToString(newdiv));
return false;
});
});
});
</script>
I think the bigger issue is asp.net changes the id and trying to get that in the code isn't that easy.
Can you use the name attribute? If so you can just look for the name attribute containing your name using the jquery selector '[ name *="YourName"]'
EDIT: I meant to add firebug is a great help for examining page elements and figuring exactly what you can use (Ex: asp.net adds a name attribute to a button by default) and whats going on (like your return false failing) then tweaking your jquery from the watch window.
Sample asp.net form content:
<p>
<asp:TextBox ID="TextBox1" name="TextBox1" runat="server" Rows="3"></asp:TextBox>
</p>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" /></p>
<p>
<asp:Label ID="Label1" name="Label1" runat="server" Text="Label"></asp:Label>
</p>
<div id="test1"></div>
jquery:
$(function () {
$('[name*= "Button1"]').click(function () {
var x = $('[name*= "TextBox1"]').val();
var newdiv = $("<div></div>").html(x).attr('id', 'test');
$('#test1').append(newdiv);
$('[name*= "Label1"]').text($('#test1').html());
$('[name*= "TextBox1"]').val('');
return false;
});
});
Here's how to do it without jQuery:
<%# Page Inherits="System.Web.UI.Page" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
<script type="text/javascript" src="App_Resources/JavaScript/jquery-1.4.4.min.js"></script>
</head>
<body>
<form runat="server">
<asp:Label ID="testLabel" runat="server" Text="test" />
<script type="text/javascript">
$(document).ready(function ()
{
var label = document.getElementById("<%= testLabel.ClientID %>");
var div = document.createElement("div");
div.innerText = "content";
label.innerText = div.outerHTML;
});
</script>
</form>
</body>
</html>