In ASP.NET (web forms), I am retrieving a set of key/value pairs from an SQL database to be used in a DropDownList. This list is quite large (can be over 2000 entries) and used multiple times over many of the pages on the website and I've been looking into ways to cache this set of data on the local client to reduce bandwidth. The list doesn't change often so having a cached copy a week or more should be fine.
I wanted to know if it was at all possible and/or practical to have this list stored using HTML5 local storage and have a DropDownList fill from the client storage. If no data if found locally, then going on to query the database for the list.
If you have over 2000 entries in a select box it dosnt sound all that usable anyway.
Have a look at something like Select2. Particularly the "Loading Remote Data" example.
http://ivaynberg.github.io/select2/
I have been involved in writing a couple of apps where data is pushed back and forth regularly and we built an API object in Javascript to handle data being pulled from the server on request.
The API module requested data and took an action depending on its success status. You could build a simple API module to use if you feel that you may need to expand the type of data returning later, or just build a single AJAX call to pull the data for the drop down list.
An example of the API interface would be as such:
/**
* Parameter 1, string - Command Name for the server to interpret
* Parameter 2, object - Data that should be passed to the server (if necessary)
* Parameter 3, string - the HTTP method to use: 'GET', 'POST', 'PUT' etc.
* Parameter 4, function - the callback to fire once the response is received.
**/
api('CommandName', { key: 'value' }, 'METHOD', function(response) {
if(response.success) {
//Store data in localStorage here
}
});
As you stated above, you are using the data multiple times throughout the pages on your website. Therefore in the JavaScript you would write a check on load which determines if the data has been stored within the localStorage, and if not makes a call to the API to populate it. This would ensure that the client always has that data available. This can be done like so:
//On Load
if(!localStorage.dropdown) {
api('CommandName', { key: 'value' }, 'METHOD', function(response) {
if(response.success) {
localStorage.dropdown = response.data;
}
});
}
Related
I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side. I'm using asp.net.
We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:
When the form submits, grab the hash (window.location.hash) and store it in a server-side hidden input field Put this in a DIV with an id of "urlhash" so we can find it easily later.
On the server you can use this value if you need to do something with it. You can even change it if you need to.
On page load on the client, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.
If the hidden input field has a valid value, set that as the URL hash (window.location.hash again) and/or perform other actions.
We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.
Before submit:
$("form").submit(function() {
$("input", "#urlhash").val(window.location.hash);
});
On page load:
var hashVal = $("input", "#urlhash").val();
if (IsHashValid(hashVal)) {
window.location.hash = hashVal;
}
IsHashValid() can check for "undefined" or other things you don't want to handle.
Also, make sure you use $(document).ready() appropriately, of course.
[RFC 2396][1] section 4.1:
When a URI reference is used to perform a retrieval action on the
identified resource, the optional fragment identifier, separated from
the URI by a crosshatch ("#") character, consists of additional
reference information to be interpreted by the user agent after the
retrieval action has been successfully completed. As such, it is not
part of a URI, but is often used in conjunction with a URI.
(emphasis added)
[1]: https://www.rfc-editor.org/rfc/rfc2396#section-4
That's because the browser doesn't transmit that part to the server, sorry.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX).
Regards
Artur
You may see also how to play with back button and browser history
at Malcan
Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).
Possible solution for GET requests:
New Link format: http://example.com/yourDirectory?hash=video01
Call this function toward top of controller or http://example.com/yourDirectory/index.php:
function redirect()
{
if (!empty($_GET['hash'])) {
/** Sanitize & Validate $_GET['hash']
If valid return string
If invalid: return empty or false
******************************************************/
$validHash = sanitizeAndValidateHashFunction($_GET['hash']);
if (!empty($validHash)) {
$url = './#' . $validHash;
} else {
$url = '/your404page.php';
}
header("Location: $url");
}
}
I have a Kendo DataSource that takes its data from a remote server (Json) and it bind the data to a kendo template in the client-side.
On the client, right now I just display the Data. However, I want to add/remove data in the dataSource as well. How can I send the dataSource after modification back to server and store it in there ?
Here is a good example of what I am trying to do. While this example reads its data from a local variable, would you please let me know:
How can I store the dataSource on the server-side after user make modification on the client ?
http://jsfiddle.net/derickbailey/D4g8S/
For example the add method just update the datasource on the client side. However, I want to send it to the Server and store it some how there. As a results, if someone else open the same web page in another client, he/she can see the changes as well.
$("#add").click(function(e){
e.preventDefault();
var $todo = $("input[name='description']");
currentId += 1;
dataSource.add({
id: currentId,
done: false,
description: $todo.val()
});
$todo.val("");
$todo.focus();
});
I am using C# .Net MVC on the server side.
As I understand you are asking how you can made server changes based on changes on client side? If is that true you can do three things:
catch data which you modify (added, deleted, updated),
Serialize to JSON,
send to the controller's action.
Here is simple example how you can read data from your datasource:
var dataSource = new kendo.data.DataSource({
data: [
{ id: 1, name: "Jane Doe", age: 30 },
{ id: 2, name: "John Doe", age: 33 }
]
});
dataSource.fetch(function(){
// reading data from dataSource
var raw = dataSource.data();
// entire dataSource
alert("This is entire dataSource: " + JSON.stringify(raw));
// this is what will be removed
alert("This is removed: " + JSON.stringify(raw[0]));
dataSource.remove(raw[0]);
// this is what is rest
alert("This is rest: " + JSON.stringify(raw));
});
After you assign these data to some object you can serialize into JSON with: JSON.stringify(data) method.
Than you can post these data to controller's action and do some work. How to post JSON to MVC controller is common question, please read here.
For deleting and updating is similar. Basically you have to catch data which you want, serialize and post to action.
You can use the add method on the data source and specify there where to post the new data. There is an example in the KendoUI documentation. From there you can also configure the edit/remove methods.
To get JSON array from dataSource object use toJSON method
dataSource.data().toJSON()
then you can post it back to the server
Demo
I'm aware that data can be passed in through the URL, like "example.com/thing?id=1234", or it can be passed in through a form and a "submit" button, but neither of these methods will work for me.
I need to get a fairly large xml string/file. I need to parse it and get the data from it before I can even display my page.
How can I get this on page load? Does the client have to send a http request? Or submit the xml as a string to a hidden form?
Edit with background info:
I am creating a widget that will appear in my customer's application, embedded using C# WebBrowser control, but will be hosted on my server. The web app needs to pass some data (including a token for client validation) to my widget via xml, and this needs to be loaded in first thing when my widget starts up.
ASP.NET MVC 4 works great with jQuery and aJax posts. I have accomplished this goal many times by taking advantage of this.
jQuery:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/{controller}/{action}/",
data: { clientToken: '{token}', foo: 'bar',
success: function (data, text) {
//APPEND YOUR PAGE WITH YOUR PARSED XML DATA
//NOTE: 'data' WILL CONTAIN YOUR RETURNED RESULT
}
});
});
MVC Controller:
[HttpPost]
public JsonResult jqGetXML(string clientToken, string foo)
{
JsonResult jqResult = new JsonResult();
//GET YOUR XML DATA AND DO YOUR WORK
jqResult.Data = //WHATEVER YOU WANT TO RETURN;
return jqResult;
}
Note: This example returns Json data (easier to work with IMO), not XML. It also assumes that the XML data is not coming from the client but is stored server-side.
EDIT: Here is a link to jQuery's Ajax documentation,
http://api.jquery.com/jQuery.ajax/
Assuming you're using ASP.NET, since you say it's generated by another page, just stick the XML in the Session state.
Another approach, not sure if it helps in your situation.
If you share the second level domain name on your two sites (i.e. .....sitename.com ) then another potential way to share data is you could have them assert a cookie at this 2nd level with the token and xml data in it. You'll then be provided with this cookie.
I've only done this to share authentication details, you need to share machine keys at a minimum to support this (assuming .Net here...).
You won't be able to automatically upload a file from the client to the server - at least not via a browser using html/js/httprequests. The browser simply will not allow this.
Imagine the security implications if browsers allowed you to silently upload a file from the clients local machine without their knowledge.
Sample solution:
Background process imports xml file and parses it. The background process knows it is for customer YYY and updates their information so it know the xml file has been processed.
A visitor goes to the customer's web application where the widget is embedded. In the markup of the widget the customer token has been added. This could be in JavaScript, Flash, iFrame, etc.
When the widget loads, it makes a request to you app which then checks to see if the file was parsed for the provided customer (YYY) if it has, then show the page/widget.
If the XML is being served via HTTP you can use Liqn to parse the data.
Ex.
public partial class Sample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://news.yahoo.com/rss/";
var el = XElement.Load(url).Elements("channel");
StringBuilder output = new StringBuilder();
foreach (var c in el.Elements())
{
switch (c.Name.LocalName.ToLower())
{
case "title":
output.Append(c.Value);
output.Append("<br />");
break;
}
}
this.Label1.Text = output.ToString();
}
}
It is not exactly clear what the application is and what kind of options you have, and what kind of control over web server you have.
If you are the owner of the web server/application your options are way wider. You can first send a file to web-server with HTTP POST or PUT, including a random token, and then use the same token for GET with token in the query string
or use other options, applicable to third party-owned websites
if you are trying to consume some auth api, learn more about it. since you are hosting web browser control, you have plenty of options to script it. including loading whatever form, setting textarea or hidden field text with your xml and then simulating a submit button click. you can then respond to any redirects and html responses.
you can also inject javascript inside the page that would send it to server with ajax request.
the choice heavily depends on the interaction model.
if you need better advice, it would be most helpful if you provided sample/simplified url/url pattern, form content, and sequence of events that is expected from you from code/api/sdk perspective. they are usually quite friendly.
There are limited number of ways to pass data between pages. Personally for this I would keep in session during the generating page and clear it when it is retrieved in the required page.
If it is generated server side then there is no reason to retrieve it from client side.
http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.100).aspx
Create a webservice that your C# app can POST the XML to and get back HTML in response. Load this HTML string into the WebBrowser control rather than pointing the control to a URL.
I have a jQuery Countdown Timer that I am using, and I need to be able to access my Database and perform some calculations and then return the result:
$('#expireMessage').countdown({until: shortly,
expiryText: '<div class="over">It\'s all over</div>'});
$('#expireMessageStart').click(function() {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#expireMessage').countdown('change', {until: shortly});
});
Now, the above code just displays a countdown timer, and counts down. And when it hits
00:00:00
it displays a message "It's all over".
But what I need it to do is display a different message depending on the result of the DB calculations.
The DB work I can do, but I'm not sure how to go about retrieving that info from the database when using jQuery. I'd really appreciate your help.
Thank you
You need to set up something on the server side to talk to the database for you, then return the result in JSON format. What that something is depends on what your server-side code is written in. Are you using PHP? Java? ASP.NET?
I work primarily in ASP.NET, so one way I might tackle this is adding a WebMethod to my page that executes a database query, builds the message, serializes it to JSON, and returns it to the client.
In your JavaScript, you'll want to execute either an XMLHttpRequest (if you're using regular JavaScript) or a jQuery AJAX request.
Here's a very simple example of what a jQuery AJAX call might look like:
$.ajax({
url: 'http://mysite.com/getmymessage',
success: function( data ) {
// Here's where you'd update your countdown display, but I'm just writing to the console
console.log( 'The server says: ' + data.myDbResult );
}
});
I have an ASP.NET page, where the user is able to trigger a console app on our server, which generates a file. What I want is the user to see a message that states 'Requesting file', then as soon as the file becomes available (i.e. File.Exists for the file returns true), the Requesting file message will change to a link of the file.
Is this easy to accomplish in ASP.NET?
In you web page implement a JSON call to a certain WebMethod which checks if the file has be been generated or not.
you can add your message in the calling function and clear it in the complete event, where you can create the link to the file also
function ddlLeaveChanged(sender, e) {
if (leaveTypeId != '-1' && dateFrom != '' && leaveStatusId != '-1') {
$('#lblMessage').show();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: WebServiceUrl + 'YourMethod',
success: FunctionSuccedded,
error: FunctionFailed
});
}
function FunctionsSuccedded(result, e) {
if (result) { $('#lblMessage').hide(); }
}
This can be achieved using a combination of:
Javascript setInterval
[jquery.Ajax][2]
ASP.NET Web Method
A javascript function can be triggered every x seconds (using setInterval) to trigger a Web Method using AJAX to check whether the file exists.
Check the links I've provided above. These should be all you need to get this working.
If you want to avoid file systems all together you could key off a database field as well, i.e. when the linked is clicked an entry is made into a database table of some sort that signifies file creation pending, and then periodically check if the status has been updated. The server side code would update that same key and have a url in the datastore as well, so you could just check for the status of file created and the link the datastore. This would also result in you having a history of file creation, which you could purge as you saw fit, so from an ASP.NET perspective you would only be relying on data access code to determine if your file was created.
Not much different in ASP.NET vs any other platform. You can go about it like this:
Make AJAX call when the triggering link is clicked.
Server-side code that handles the call launches an external process to generate the file, and waits for it to complete.
After checking that the file is indeed there, reply to the AJAX call with a meaningful message (i.e. one that contains enough information to build a link to the file).