Dynamically search database and show results using Javascript and C# - c#

I want to search a database for a clientName and dynamically show the results while the user is typing so they can select a User. It is now my understanding that this cannot be done without using javascript.
So if the user is typing "Al" then reults of clients called "Allan, Alison, Ali..." etc would show in a dropdownlist like display under it.
At the moment the user is entering the Clients name into a Textbox.
I know that creating the DropDownList should be done something like this:
private void InitializeNameDropDown(DataTable dtTable)
{
string ClientName = Clienttb.Text;
MySqlDataReader Reader = MySQLQuery(ClientName);
int nTotalRecords = dtTable.Rows.Count;
for (int i = 0; i < nTotalRecords; i++)
{
NameDropDown.Items.Add(dtTable.Rows[i]["Client"].ToString());
}
}
MySQLQuery() just checks that the client exists within the database.
But I don't know how to dynamically interact with the database to return the results as the user is typing.
Any Help will be appreciated, Thank you in advance.

You can do it without JS, hang event on text change on TextBox (OnTextChanged), and in there update DDL ( dont forget to set AutoPostBack=true ).
But it can easily make user wait ( "freeze page" ), or even rollback what he wrote if you are using Ajax.NET
I strongly recommend using JS rather then this ( use JS and WCF/ashx/regular WS, any of these will do ) due to performance gain and much better possibilities of customization.
ASP anyway generates a load of JS for "ASP controls".
This can be applied for example http://www.codeproject.com/KB/aspnet/Cross_Domain_Call.aspx

You'll have to hook into the keyup event on the text box and fire an XmlHttpRequest from that event - if you're using jQuery it's pretty simple:
$('#mytextbox').keyup(function() { $.ajax(blah blah) });
Alternatively, as Dennis says, just use the auto-complete plugin - it's very simple and works well.

As for the client side try jquery and jqueryui's autocomplete, it's just a suggestion, jquery has a nice ajax call and it's really simple to use, and for the jqueryui autocomplete, you just pass it keywords and it will create a list right under the input box.
http://jquery.com/
http://jqueryui.com/
http://api.jquery.com/jQuery.ajax/

Here's some code that might get you going.
It uses the jquery Javascript library. It assumes you're getting the full HTML of the results list that you want to display to the user. You'll need more Javascript to dynamically show/hide the box that contains the list. You'll also need a server-side script that gets a collection of search results based on some search text. That script should be located at the URL defined in the #searchPartialUrl tag (which can be hidden). The search text should be in an input called #searchText.
I like this method because you can maintain your JS code in a separate file and reuse it. Your server just needs to create HTML views that have all the async target information in regular HTML tags.
I also implemented a delay between checking key-events so that you're not constantly sending requests to your server. (I got this method from another answer on stackoverflow, but I can't seem to find it now. I'll give credit when I do.)
// This function is used to delay the async request of search results
// so we're not constantly sending requests.
var mydelay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
var asyncSearchForm = function(onSuccess) {
var keyupWrapper = function(keyCode) {
// if this key was an arrow key, then
// ignore the press
for (var i = 37; i <= 40; i++)
if (keyCode == i)
return;
// get all the search info from the form
var searchText = $('#searchText').val();
var searchPartialUrl = $('#searchPartialUrl').val();
// make the ajax call
$.ajax({
type: "POST",
url: searchPartialUrl,
data: {
searchText: searchText
},
dataType: "html",
// on success, the entire results content should be replaced
// by the results returned
success: function(data, textStatus, jqXHR) {
$('#searchResults').html(data);
onSuccess();
},
// on error, replace the results with an error message
error: function(jqXHR, textStatus, errorThrown) {
$('#searchResults').html('<p>An error occurred while getting the search results.</p>');
}
});
};
onSuccess = (typeof (onSuccess) == 'undefined') ? function() { } : onSuccess;
// On each key-up event, we'll search for the given input. This event
// will only get triggered according to the delay given, so it isn't
// called constantly (which wouldn't be a good idea).
$('#searchText').keyup(function(e) {
// delay between each event
mydelay(function() {
// call key up
keyupWrapper(e.keyCode);
}, 500);
});
}
Update:
You said you're using C#. If you're using MVC, you'll need an action in your controller to be a target for your async request. Here's an example:
[HttpPost]
public ActionResult GetSearchResults(string searchText)
{
// Here, you should query your database for results based
// on the given search text. Then, you can create a view
// using those results and send it back to the client.
var model = GetSearchResultsModel(searchText);
return View(model);
}

Related

Run C# function after two ASP TextBoxes have been filled

I've been all over trying to find an answer to this, but every answer I found seemed to differ quiet a bit from what I really am looking for.
I need to check to make sure that two ASP Textboxes have been filled in before running a C# function that will do work on the text boxes.
Currently, I am using codebehind to check, but it is sloppy and has to postback to work.
So I have:
<td>Start Date (mm/dd/yyyy):</td><td><asp:TextBox ID="startDate" runat="server"></asp:TextBox></td>
<ajax:CalendarExtender ID="ce1" runat="server" TargetControlID="startDate"></ajax:CalendarExtender>
<td>End Date (mm/dd/yyyy):</td><td><asp:TextBox ID="endDate"></asp:TextBox></td>
<ajax:CalendarExtender ID="ce2" runat="server" TargetControlID="endDate"></ajax:CalendarExtender>
So I need a JS function to check if both field are empty, before using AJAX to run a C# program. I'm new to ASP and JS but this problem came through and figured it would be a (sort of) easy fix.
I would assume something like:
function checkDates(startid, endid) {
var s = document.getElementById(startid);
var e = document.getElementById(endid);
if( s != '' && e != ''){
//Use ajax to run C# function
}}
should work. But I can't seem to find any examples close to it to get an idea of what I need to do when working ASP and not just HTML.
Any input is greatly appreciated! (I tried to be as clear as possible, getting tunnel vision..)
You are almost there
function checkDates(startid, endid) {
var s = document.getElementById(startid);
var e = document.getElementById(endid);
if( s.value != '' && e.value != ''){
//Use ajax to run C# function
}
}
You should also need to check on the server side to ensure that the parameters being supplied are not null or empty.
This should work for you. I built an object to help keep things organized. Get the elements using the ClientID and store the reference in an object.
Whatever you're binding the handler to just needs to call Page.Handlers.CheckDates();
var Page =
{
Members:
{
startDate: document.getElementById('<%=startDate.ClientID %>'),
endDate: document.getElementById('<%=endDate.ClientID %>')
},
Handlers:
{
CheckDates: function ()
{
if (Page.Members.startDate.value.length > 0 && Page.Members.endDate.value.length > 0)
{
Page.Ajax.ValidateDates();
}
}
},
Ajax:
{
ValidateDates: function ()
{
//Put you ajax code here
}
}
}
In addition to Kami's answer I believe asp.net automatically prepends a tag to all asp.net controls to distinguish them. If you haven't changed it yourself I believe the default is "ct100_". So if you're using jQuery and aren't use an ajax call to get the ClientID the selector would look something like "#ct100_idname".
http://www.asp.net/web-forms/tutorials/master-pages/control-id-naming-in-content-pages-cs
Edit:
You can also use an inline server call to get the ID of a asp.net control
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx

update viewmodel in knockout and update the UI

below is my javascript that loads the model and i binded it to a dropdown and a table to show data. which works and shows the data.
var _observableViewModel = null;
$(document).ready(function () {
var jsonModel = '#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model))';
_observableViewModel = ko.mapping.fromJSON(jsonModel);
ko.applyBindings(_observableViewModel);
});
once a user selects the an item from the dropdownlist i am calling a ajax function that returns jsonresult and want to update the viewmodel and update the table as well. i tried something below but no effect.
i am using mvc.
thanks for the help!
function GetData() {
$.getJSON("/Home/Test", function (data) {
ko.mapping.updateModel(data);
})
since you are already using ko.mapping you really should use the mapping overload specifying a target :
ko.mapping.fromJSON(jsonModel, {}, _observableViewModel)
It will update the observable as before, as well as calling the observable valueWillMutate / valueHasMutated methods to update the UI.

Running JavaScript in page from the backend (AJAX)?

I'm new to integrating JavaScript into a web site, but I'm going to need it often in my web site.
Here is an example:
Assuming I have the function:
showAlert()
Say I have:
<div id="some_div">
</div>
Could someone provide me some kind of example that would do this:
If I have a button and the user clicks it, this should raise an event in the backend and call some method in my C# file. Then my C# file should be able to call some other javascript method of the front end which would call showAlert() and display the alert in the div.
This is what I can't seem to find any information on.
The basic idea of passing information to and from the server. Any help with this would be really appreciated.
Thanks
Your best bet is to use a framework like jquery, then bind to the button, call the service, and handle the response. The below is a quick example of this.
$(document).ready(function()
$('#Button1').bind('click', function () {
// This grabs the page you are in so that you can call it correctly
var pagePath = window.location.pathname;
var testId = $("#some_div").val();
var url = pagePath + "/TestService";
$.post(url, { id: testId },
function (data) {
showAlert(data);
}
});
};
});
First, you need to make sure the document is ready at some point. Bind allows the the button to be bound when the document loads. Then, by clicking it, you execute the anonymous function that grabs the testId, calls your service, and handles the data response in a success callback.
Hope that gets you started in the right direction!
EDIT: Added backend webforms "service" exposure
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestService(string id)
{
var string = DBCollection.FirstOrDefault(x => x.id == id); // Or whatever you want to return the data
return "You called me on " + DateTime.Now.ToString() + "with " + string;
}
}
This would allow you to call the "WebMethod exposed on your page. For more help with this, please see the following link.
http://www.tugberkugurlu.com/archive/asp-net-web-forms---calling-web-service-page-methods-using-jquery
EDIT: Additional Considerations when performing this type of approach in webforms.
Calling a webmethod with jquery in asp.net webforms

Passing prompt box value from javascript function- PostBack to c#

I'll try to do the best I can to articulate what I'm trying to do.
Let me preface by saying that I am very new to C# and ASP.NET and have minimal experience with javascript.
I have a javascript function that invokes a prompt box. The overall picture is - if input is entered - it will be saved to a column in the database.
I'm drawing a blank on passing the value from the prompt box to the PostBack in c#.
function newName()
{
var nName = prompt("New Name", " ");
if (nName != null)
{
if (nName == " ")
{
alert("You have to specify the new name.");
return false;
}
else
{
// i think i need to getElementByID here???
//document.forms[0].submit();
}
}
}
This is what I have in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//I have other code that works here
}
else
{
//I'm totally lost here
}
}
I'm trying to figure out how to make that call for the input from the javascript function.
I've spent the last few hours looking online and in books. Been overwhelmed.
EDIT
i did a little tweeking to fit what I'm trying to do....
<asp:HiddenField ID="txtAction" runat="server" Value="" />
document.forms(0).txtAction.Value = "saveevent";
document.forms(0).submit();
trying to figure out how to insert the string into the table now.....
string nEvent = Request.Form["event"];
if (txtAction.Value == "saveevent") {
nName.Insert(); //am i on the right track?
}
Well, here's one possible way (untested but should give you the basic idea). You could place a hidden field on your form to hold the value of the prompt:
<input type="hidden" id="hiddenNameField" runat="server" value="">
Then prompt the user for the value, set it to the hidden field, and then submit your form:
document.getElementById('hiddenNameField').value = nName;
document.forms(0).submit();
Then in your code-behind you can just access hiddenNameField.Value.
if you are trying to call the method on the back side using the java script you can try using the web method approach.
for instance you have a function that will call the SendForm method
function SendForm() {
var name = $("#label").text();
PageMethods.SendForm(name,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
}
function OnFailed(error) {
}
and you have the method that will be called from javascript.
[WebMethod(enableSession: true)]
public static void SendForm(string name)
{
}
<script language='Javascript'>
__doPostBack('__Page', '');
</script>
Copied from Postback using javascript
I think you need AJAX request here. I suggest usage of jQuery, since do the dogs work for you... Otherwise, you will have to implement a lot of already written general code for AJAX processing.
Something as the following one:
function PromptSomewhere(/* some args if needed*/)
{
var nName = prompt("New Name", " ");
// Do process your prompt here... as your code in JS above. Not placed here to be more readable.
// nName is used below in the AJAX request as a data field to be passed.
$.ajax({
type: "post", // may be get, put, delete also
url: 'place-the-url-to-the-page',
data {
name: nName
// You may put also other data
},
dataType: "json",
error: PromptFailed,
success: OnPromptComplete
});
}
function PromptFailed(xhr, txtStatus, thrownErr) // The arguments may be skipped, if you don't need them
{
// Request error handling and reporting here (404, 500, etc.), for example:
alert('Some error text...'); // or
alery(txtStatus); // etc.
}
function OnPromptComplete(res)
{
if(!res)
return;
if(res.code < 0)
{
// display some validation errors
return false;
}
// display success dialog, message, or whatever you want
$("div.status").html(result.message);
}
This will enable you to send dynamically data to the server with asynchronous request. Now C#:
using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string nName = Request.Form["name"];
// do validation and storage of accepted value
// prepare your result object with values
result.code = some code for status on the other side
result.message = 'Some descriptive message to be shown on the page';
// return json result
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(result));
}
}
Notes: If you use ASP.NET MVC 2 or higher I think, you will be able to use JsonResult actions and Request.IsAjaxRequest (I think was the name), and many other facilities and improvements of ASP.NET - ASP.NET MVC is the new approach for creating web applications based on MVC pattern (architecture) and will replace ASP.NET Pages eventually in some time.
This is a very good resource and contains the answer to your question:
How to use __doPostBack()
Basically, call PostbackWithParameter() function from your other JS function:
<script type="text/javascript">
function PostbackWithParameter(parameter)
{
__doPostBack(null, parameter)
}
</script>
And in your code-behind, grab the value for that parameter like so:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
}

javascript + asp.net - Calling javascript functions from c# and passing an object

I'm fairly new to web development.
Basically I'm using a HTML5 canvas to render content, and javascript functions which clear and render to the canvas.
I'm hoping to call a web service to get data that would affect content, which I believe is most easily done from C#, and was wondering how I could use this to periodically call a javascript function that would update values that are being rendered to the canvas?
To make this clearer, I have something like this:
Oh I'm also using jquery by the way, partly because I was told to.
Page.asp:
<body>
<form id="form1" runat="server">
<canvas id="canv" width="200" height="200">
Cannot display canvas because your web browser is a fail.
</canvas>
<script type="text/javascript">
var ctrls = new Array();
$(document).ready(function () {
var canvas;
var context;
canvas = $("#canv").get(0);
if (!canvas) {
alert("Failed to get canvas");
return;
}
context = canvas.getContext('2d');
if (!context) {
alert("Failed to get context");
}
var x;
x = new Object();
x.value = 0;
x.parent2d = context;
ctrls.push(x);
window.setInterval(Render, 25);
});
function Render() {
var i;
for (i = 0; i < ctrls.length; i++) {
ctrls[i].parent2d.clearRect(0, 0, 200, 200);
//Draw stuff.
}
}
function Update(newVal) {
var i;
for (i = 0; i < ctrls.length; i++) {
ctrls[i].value = newVal; //For example
}
}
</script>
</form>
</body>
What is the easiest (if it's even possible) way to call the Update(newVal) function from C# (Page.asp.cs), and how could this be set up to be done periodically?
What would be the limitations on what object(s) could be passed to this function?
Dictionary<String, Double>
would be very useful.
When exactly does update need to be called after page load? If it's every five seconds, it might be easier to carefully set up some sort of Javascript-based interval (making sure you are checking certain conditions to ensure that the interval quits upon any error conditions).
Depending on what data you have, you may want to setup a method in C# that given certain POST or GET parameters passed to it via a jQuery $.ajax() call.
For instance:
$(document).ready(function() {
var intervalId = setInterval("runUpdate()", 5000);
});
function runUpdate() {
//Make an ajax call here, setting up a variable called 'data'
update(data);//Data is newVal, which was setup in the ajax call above
}
That code would run the update function every five seconds.
Firstly from Javascript I would normally avoid using xml based web services. The returned data is XML which has lots of unessesary tags which can cause transfer to be slow.
Instead look at JSON. Its much faster. However not so easy for authentication. To help you understand its power both twitter and facebook use it in there APIs.
JQuery can consume JSON really easy
$.getJSON(someurl, function(jData) {
//use returned data
}
You might find it useful to read this:
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
Hope this helps.

Categories