update session variable on textbox_change without postback - asp.net

is there any way to save textbox text to a session variable without having to postback on text change?

You will need to do this in 4 stages.
1) Add an onkeydown="textChanged(this.ID);" to your textbox
2) Use some Javascript to capture the text
3) Fire an Ajax call to a web method
4) use the web method to store the session variable.
So something like this:
On your textbox, set Autopostback=false so you don't post back on typing.
Create yourself a small Javascript function that will be fired when the user types.
this function will first clear any timer attached to the textbox. then it will create another one that will fire another function after 1 second. This will ensure you're not trying to fire the end function too often.
function textChanged(id) {
var txtBox = document.getElementById(id);
clearTimeout(txtBox.timer);
txtBox.timer = setTimeout('SaveVariable()', 1000);
};
After 1 second, your method will call something like this:
function SaveVariable(){
// Do an ajax call in here and send your textbox value to a web method
var t = // GetYourTextboxTextHere
if (t != "") {
$.ajax({
type: "POST",
url: "yourPage.aspx/SaveMyTextVar",
data: "{'textToSave ': '" + escape(t) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (!msg.d) {
// it didn't save
} else {
// it saved just fine and dandy
};
}
});
};
}
Finally, a small web method on your code behind to capture the text
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> <Services.WebMethod()> _
Public Shared Function SaveMyTextVar(ByVal textToSave As String) As Boolean
'' Save your variable to session here.
'' return true or false
'' you can capture the returning result in the AJAX that calls this method
End Function

Related

FullCalendar plugin not rendering events on calendar

I am using fullCalendar plugin to display events from ASP.NET ASMX web service. JSON data is fetched correct and displayed ok in the console. But events are not rendered on the calendar view. What am I missing?
$('#divcalendar').fullCalendar({
defaultDate: '2018-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: function (start, end, timezone,callback) {
$.ajax({
type: "POST",
url: 'Webservice.asmx/ListEvents',
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var event = [];
$(data.d).each(function () {
event.push({
title: this.Title,
start: this.Start,
end: this.End
});
});
console.log(event);
callback(event);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('There was an error');
}
});
}
});
[WebMethod]
public CalendarEvent[] ListEvents()
{
DateTime epoc = new DateTime(1970, 1, 1);
return new CalendarEvent[]
{
new CalendarEvent { Title = "Event 1", Start = new DateTime(2018,3,9,16,0,0).Subtract(epoc).TotalSeconds, End = new DateTime(2018,3,9,17,0,0).Subtract(epoc).TotalSeconds},
new CalendarEvent { Title = "Event 2", Start = new DateTime(2018,3,12,12,0,0).Subtract(epoc).TotalSeconds, End = new DateTime(2018,3,12,13,0,0).Subtract(epoc).TotalSeconds}
};
}
Console output from webservice
{"d":[{"__type":"CalendarEvent","End":1520614800,"Start":1520611200,"Title":"Event 1"},{"__type":"CalendarEvent","End":1520859600,"Start":1520856000,"Title":"Event 2"}]}
I think your dates are being entered into the calendar, but not in the place you intended.
Although you haven't mentioned it explicitly, I would strongly suspect that the timestamps you're outputting for your start and end dates are specified in seconds.
Now, fullCalendar uses momentJS to parse any date strings or timestamps supplied to it. Alternatively it can accept ready-made momentJS or JS Date objects.
momentJS can parse timestamps automatically through the momentJS constructor (which fullCalendar is calling when it receives your timestamp value), but it assumes the value is given in milliseconds, not seconds.
Therefore when you supply it with, for instance, 1520611200 (the start date of your first event), it interprets that in milliseconds and the resulting date is 1970-01-18 14:23:31.
If you want to specify the date in seconds you have to use the moment.unix() method instead. Using this method, your timestamp is instead interpreted as 2018-03-09 16:00:00, which I assume is what you intended.
See http://jsfiddle.net/Loccoxds/1/ for a demo to see the difference in how momentJS parses one of your values.
To get your code working, the simplest way is to do this:
success: function (data) {
var event = [];
$(data.d).each(function () {
event.push({
title: this.Title,
start: moment.unix(this.Start),
end: moment.unix(this.End)
});
});
console.log(event);
callback(event);
},
This way, you supply a ready-made momentJS object to fullCalendar, having correctly parsed the timestamp.
See http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/ for more details about parsing timestamps in momentJS
P.S. Alternatively of course you could change your asmx service to output the dates in a format momentJS can parse automatically, such as a timestamp in milliseconds, or an ISO8601-formatted date string - see http://momentjs.com/docs/#/parsing/string/ for details of that.
P.P.S. ASMX is pretty much a legacy technology within .NET now. You should consider using WCF or Web API instead. Microsoft recommends not to create new code using ASMX.

file upload controlasp.net and ajax

hey i am have made a form for product detail insertion . I am using ajax in asp.net in order to insert data in database. Now in my form of the controls is fileupload control. Problem is i dont know how to select the file and pass it to the static method for operations like hasfile, etc. so is it possible that i pass the file using ajax technique and can store it's detail in database.
<asp:FileUpload ID="file_image" runat="server" />
$(document).ready(function () {
$("#submit").click(function () {
var cat = document.getElementById('DropDownList1').value;
var nm = document.getElementById('name').value;
var code = document.getElementById('code').value;
var dt = document.getElementById('dt').value;
var price = document.getElementById('price').value;
alert("you clicked " + cat + " - " + nm + "-" + code + "-" + dt + "-" + price + "-");
var fl = document.getElementById('file_image').value;
//this line is the problem as i can't get file
$.ajax({
method: "POST",
contentType: "application/json",
url: "~/home.aspx/insert",
dataType: "json",
// data: "{'Name':'" + document.getElementById('name').value + "'}",
data:"{}",
//async: false,
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
})
});
There are some issues with uploading files via ajax.
Ref. jQuery Ajax File Upload
You can do it as shown in the following link; however, it won't work in IE <= 9. http://blog.teamtreehouse.com/uploading-files-ajax
My recommendation if you want to upload multiple files would be to use something like http://www.uploadify.com/ with automatic fallback support. That way, you don't have to spend time programming that stuff yourself.

Returning several arrays as a Json result, how can I serialize the response on the server?

When the Action method below attempts to return the Json result no data object comes back to the $.ajax function. Hence I presume I am not serializing the arrays prior to sending them off as a Json result. I need to retain the array names i.e: ProgTypes, Ages etc. So I know which array is which when the data returns from the server.
$.ajax({
url: '/Education/FilterLists',
dataType: 'json',
data: { svalues: svalues, firsttype: $firsttype },
traditional: true,
success: function (data) {
//do something with data
alert('done');
}
});
..
public JsonResult FilterLists(int[] svalues, string firsttype)
{
//Some logic takes place and below arrays are produced
int[] ProgTypes = programs.Select(x => x.FilterValToCatMaps.FirstOrDefault(c => c.FilterValue.FilterID == 5).FilterValueID).Distinct().ToArray();
int[] Ages = programs.Select(x => x.FilterValToCatMaps.FirstOrDefault(c => c.FilterValue.FilterID == 4).FilterValueID).Distinct().ToArray();
int[] Countries = programs.Select(x => x.ParentCategory.ParentCategory.ParentCategory.CatID).Distinct().ToArray();
return Json(new { progtypes = ProgTypes, ages = Ages, countries = Countries});
}
You are attempting to retrieve JSON data via a GET request (jQuery AJAX implicitly does a GET unless you specify the "type: 'POST'" option"). ASP.NET blocks JSON returning GETs for security reasons with an exception of this message:
"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."
Your success function is never getting executed because the request isn't a success. I would recommend getting FireBug for FireFox and using the 'Net' tab or use chromes built in debugger and use the 'Network' tab if you are going to be doing any web development (especially AJAX). Network errors pop right up in there and it can save you a lot of time.
You have two options at this point, change your .NET code or change your JavaScript, pick one below:
$.ajax({
url: '/Education/FilterLists',
dataType: 'json',
type: 'POST', //ADD POST HERE
data: { svalues: svalues, firsttype: $firsttype },
traditional: true,
success: function (data) {
//do something with data
alert('done');
}
});
OR
return Json(new { progtypes = ProgTypes, ages = Ages, countries = Countries}, JsonRequestBehavior.AllowGet);

How do i bind the json data to a asp.net dropdownlist using jquery?

I am trying to design a cascading dropdown. i am using 3 asp.net dropdowns. THe first one on page load loads the countries. Then when a country is selected i do a ajax call to a webmethod. I fetch the data for the teams belonging to that country. The data is in a dataset which i convert into JSON and then return it. On success what code do i need to add to bind the json data to the dropdown list.
below is the code.
$(document).ready(function() {
$('#ddlcountries').change(function() {
debugger;
var countryID = $('#ddlcountries').val();
$.ajax({
type: "POST",
url: "Default.aspx/FillTeamsWM",
data: '{"CountryID":' + countryID + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(jsonObj) {
/* WHAT CODE DO I ADD HERE TO BIND THE JSON DATA
TO ASP.NET DROP DOWN LIST. I DID SOME GOOGLING
BUT COULD NOT GET PROPER ANSWER */
},
error: function() {
alert('error');
}
});
});
});
Depending on what you're passing back to the client, I am going to assume it's a List<string>. You can adjust the code accordingly depending on what you're passing back to the client, since you're not telling us what is being passed back.
So if that is the case do something like this:
// first remove the current options if any
$('#ddlTeams').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(jsonObj).each(function(index, item){
$('#ddlTeams').append($('<option></option>').val(item).html(item));
});
Assuming again, if your List has an object containing teamid and `teamname11
// first remove the current options if any
$('#ddlTeams').find('option').remove();
// next iterate thru your object adding each option to the drop down\
$(jsonObj).each(function(index, item){
$('#ddlTeams').append($('<option></option>').val(item.teamid).html(item.teamname));
});
It is dependent on the data you are getting back from the server but this is what I came up with presuming it was a simple json structure, I was also wondering whether it may be better to send the data on the first request, and forget about the ajax.
$('#continent').change(function() {
// success function
$('#country').children().remove();
for (var country in json.continents[$(this).val()]) {
var $elm = $('<option>').attr('value', country)
.html(country);
$('#country').append($elm);
}
})
Here is a demo;
Edit: Given your data structure have update so something like this
var teams = json['TeamList'];
$('#teamid').change(function() {
// success function
var $t = $(this);
var $select = $('#teamname');
var i = (function() {
for (var i=0; i<teams.length; i++) {
if (teams[i]['teamid'] == $t.val()) {
return i;
}
}
})()
var name = teams[i]['teamname'];
var $elm = $('<option>').val(name).html(name);
$select.children().remove();
$select.append($elm);
})
see here for demo, please note this may requiring some changing to fit your specific use case, but it demonstrates simple iteration over arrays and objects

How to call JQuery Ajax Post with querystring URL

I have a web page which is redirected from a another page and have a querystring in it. now this page is calling a Jquery AJAX call to do some other task.
Page URL is like : http://localhost:1041/Inventory/Inventorydetail.aspx?invoiceid=3
now this page is calling a AJAX post to delete a record from the grid.
$(".DeleteInvoiceLine").click(function() {
//Get the Id of the record
var record_id = $(this).attr("id");
var loc = window.location;
// Ask user's confirmation
if (confirm("Do you want to delete this record?")) {
$.ajax({
type: "POST",
url: loc + "/DeleteInvoiceLineEntry",
//Pass the selected record id
data: "{'args': '" + record_id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msgstr) {
var msg = $("#ctl00_ContentPlaceHolder1_success");
msg.html(msgstr.d);
msg.show();
}
});
}
return false;
});
so when I call the AJAX call the page_Load event is called instead of the webmethod "DeleteInvoiceLineEntry".
if I have my page without the querystring passed it works fine.
could you please suggest me how I can call a AJAX call on the page which has a querystring data init.
I tried it both way passing the static URL
Not working
url: "Inventorydetail.aspx?invoiceid=3/DeleteInvoiceLineEntry"
Working (if there is no querystring data in the page)
url: "Inventorydetail.aspx/DeleteInvoiceLineEntry"
Thanks for your quick help.
Don't attach query string when you call ajax. It will confuse the communication as ajax actually use query string to pass json data. If you want to pass invoiceid to the ajax, include it in json data.
Change
var loc = window.location;
To
var loc = window.location.href.replace(window.location.search, '');
as Taesung Shin mentioned. The query string in the URL is confusing your application.

Resources