ASP.NET display progress bar during post back - asp.net

I have a fileupload control on a form and a button. Once a button is clicked the server converts the file into a datatable and loops through datatable records for validation purposes.
My problem: the validation process takes a long time, so i wanted to display current item being processed to user.
My attempts: i found Ajax and SignalR being implemented in such scenarios. However, Ajax requires an update panel to work which cannot work with the updatefile control. I tried SignalR and it works however, it cannot work during a postback --> apparently.
Can anyone assist me in finding a solution.
Thank you!

Hey you can use ModalPopupExtender of ajaxToolkit something like this
<ajaxToolkit:ModalPopupExtender ID="ProgressBarModalPopupExtender" runat="server"
BackgroundCssClass="ModalBackground" BehaviorID="ProgressBarModalPopupExtender"
TargetControlID="hiddenField" PopupControlID="Panel1" DynamicServicePath="" Enabled="True" />
<asp:Panel ID="Panel1" runat="server" Style="display: none; background-color: #C0C0C0;">
<p class="wait">Please wait!</p>
</asp:Panel>
<asp:HiddenField ID="hiddenField" runat="server" />
add the above code any where on your page then on your button of file upload try this
<input type="submit" value="Upload" id="upload"
causesvalidation="False" onclick="javascript:return validateAdd();"
onserverclick="btnupload_ServerClick" runat="server" />
in javascript
function validateAdd() {
var myExtender = $find('ProgressBarModalPopupExtender');
myExtender.show();
return true;
}
and in code behind
protected void btnupload_ServerClick(object sender, EventArgs e)
{
// your code of upload
//
// your code of upload
ProgressBarModalPopupExtender.Hide();
}
this shall do

If you only target HTML5 users you can use the FileReader class and stream the file with ajax. This will work with SignalR
I did it like this in my project, maybe it can give you some pointers
(function(app) {
app.FileUploadViewModel = app.define({
init: function (parent, file, callback) {
this.kb = 1024;
this.bufferSize = this.kb * 512;
this.speedSampleAt = this.bufferSize;
this.file = file;
this.parent = parent;
this.reader = new FileReader();
this.total = this.file.size / this.bufferSize;
this.current = ko.observable(0);
this.progress = ko.computed(this.getProgress, this);
this.speed = ko.observable(0);
this.speedText = ko.computed(this.getSpeedText, this);
this.name = this.file.name;
this.reader.onload = this.onLoadPart.bind(this);
this.callback = callback;
this.createStream();
},
prototype: {
createStream: function() {
app.utils.post("api/upload/createstream", {
parentId: this.parent.id,
filename: this.file.name
}, function (id) {
this.id = id;
this.loadPart();
}.bind(this));
},
getSpeedText: function() {
return Math.round(this.speed()) + " Mbit / s";
},
getProgress: function () {
return (this.current() / this.total * 100) + "%";
},
loadPart: function () {
var start = this.current() * this.bufferSize;
this.calculateSpeed(start);
var blob = this.file.slice(start, start + this.bufferSize);
this.done = blob.size != this.bufferSize || blob.size === 0;
this.reader.readAsDataURL(blob);
},
onLoadPart: function (part) {
if (part.loaded === 0) {
this.onPartTransfered();
} else {
var base64 = part.target.result.substr(part.target.result.indexOf(",") + 1);
app.utils.post("api/upload/Part", { id: this.id, data: base64 }, this.onPartTransfered.bind(this));
}
},
onPartTransfered: function () {
this.current(this.current() + 1);
if (this.done) {
this.callback(this);
app.utils.post("api/upload/closestream", this.id, function (file) {
this.parent.addChild(file);
}.bind(this));
} else {
this.loadPart();
}
},
calculateSpeed: function (position) {
if (this.lastSpeedSample === undefined) {
this.lastSpeedSample = new Date();
}
if (position % this.speedSampleAt === 0) {
var delta = new Date() - this.lastSpeedSample;
var seconds = delta / 1000;
var mbit = this.speedSampleAt / this.kb / this.kb * 8;
var speed = mbit / seconds;
this.lastSpeedSample = new Date();
this.speed(speed);
}
}
}
});
})(window.Filebrowser = window.Filebrowser || {});

Related

Photo Upload in ASP.NET

I have an image box and a Photo Upload control with a Save button. I need to upload an image into the Image Box.
When I click the Upload button, it should show the Image in the Image Box.
When I click the Save button, the path of the uploaded image should be saved in the database.
My issue is the photo gets uploaded, but only after I click the Upload button for the second time.
P.S. I use a Client side function for uploading the photo.
Following are my codes.
CLIENT SIDE FUNCTION FOR UPLOADING THE PHOTO
function ajaxPhotoUpload() {
var FileFolder = $('#hdnPhotoFolder').val();
var fileToUpload = getNameFromPath($('#uplPhoto').val());
var filename = fileToUpload.substr(0, (fileToUpload.lastIndexOf('.')));
alert(filename);
if (checkFileExtension(fileToUpload)) {
var flag = true;
var counter = $('#hdnCountPhotos').val();
if (filename != "" && filename != null && FileFolder != "0") {
//Check duplicate file entry
for (var i = 1; i <= counter; i++) {
var hdnPhotoId = "#hdnPhotoId_" + i;
if ($(hdnPhotoId).length > 0) {
var mFileName = "#Image1_" + i;
if ($(mFileName).html() == filename) {
flag = false;
break;
}
}
}
if (flag == true) {
$("#loading").ajaxStart(function () {
$(this).show();
}).ajaxComplete(function () {
$(this).hide();
return false;
});
$.ajaxFileUpload({
url: 'FileUpload.ashx?id=' + FileFolder + '&Mainfolder=Photos' + '&parentfolder=Student',
secureuri: false,
fileElementId: 'uplPhoto',
dataType: 'json',
success: function (data, status) {
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
$('#hdnFullPhotoPath').val(data.upfile);
$('#uplPhoto').val("");
$('#<%= lblPhotoName.ClientID%>').text('Photo uploaded successfully')
}
}
},
error: function (data, status, e) {
alert(e);
}
});
}
else {
alert('The photo ' + filename + ' already exists');
return false;
}
}
}
else {
alert('You can upload only jpg,jpeg,pdf,doc,docx,txt,zip,rar extensions files.');
}
return false;
}
PHOTO UPLOAD CONTROL WITH SAVE BUTTON AND IMAGE BOX
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server" Height="100px" Width="100px" ClientIDMode="Static" />
<asp:FileUpload ID="uplPhoto" runat="server" ClientIDMode="Static"/>
<asp:Label ID="lblPhotoName" runat="server" Text="" ForeColor ="Green" ClientIDMode="Static"></asp:Label>
<asp:Button id="btnSave" runat="server" Text="Upload Photograph" onClick="btnSave_Click" OnClientClick="return ajaxPhotoUpload();"/>
</td>
</tr>
</table>
SAVE BUTTON CLICK EVENT IN SERVER SIDE (to show the uploaded image in the image box)
Protected Sub btnSave_Click(sender As Object, e As EventArgs)
Image1.ImageUrl = hdnFullPhotoPath.Value
End Sub
I’d recommend that you drop client side AJAX upload via JS and stick to standard way of uploading. You can probably achieve the same effects without the excessive javascript.
If file type filtering is an issue you can check this post for more details.
Getting extension of the file in FileUpload Control
In either way you have to make a postback so it doesn’t really matter if you upload from JS or the server side except that second method is less complex.
Adding update panel will make this more user friendly and you should be all done.
<head runat="server">
<title>Index</title>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/ajaxupload.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type="button" id="uploadFile" value="Upload File" />(jpg|jpeg|png|gif)
<div id="uploadStatus" style="color: Red">
</div>
</div>
<script type="text/javascript" language="javascript">
new AjaxUpload('#uploadFile', {
action: 'Handler1.ashx',
name: 'upload',
onComplete: function (file, response) {
if (response == '0') {
$('#uploadStatus').html("File can not be upload.");
}
else {
$('#img').attr("src", "response.path");
}
},
onSubmit: function (file, ext) {
if (!(ext && /^(jpg|jpeg|png|gif)$/i.test(ext))) {
$('#uploadStatus').html("Invalid File Format..");
return false;
}
$('#uploadStatus').html("Uploading...");
}
});
</script>
Then create a handler for uploading image on server
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string a = "1";
if (context.Request.Files != null && context.Request.Files.Count > 0)
{
if (context.Request.Files[0].ContentLength > 1000)
{
a = "0";
}
}
else
{
a = "0";
}
context.Response.Write(a);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
All, thanks for your time and help.! The tilde(~) symbol was the issue - the file's path wasn't recognized. So I modified my code to replace it with empty space.
var orgpath = data.upfile;
var photopath = orgpath.replace('~/', '');
$('#<%= ImgFacultyPhoto.ClientID%>').attr('src', photopath);

How to check file size of each file before uploading multiple files in ajaxtoolkit ajaxfileupload control in asp.net?

<cc1:AjaxFileUpload ID="AjaxFileUpload1" AllowedFileTypes="jpg,jpeg"
runat="server" MaximumNumberOfFiles="4" OnUploadComplete="AjaxFileUpload1_UploadComplete"
/>
Code behind file
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if (e.FileSize > 10)
{
string filePath = e.FileName;
AjaxFileUpload1.SaveAs(Server.MapPath(filePath));
}
else
{
}
}
I want to check that all the files size should not exceed a particular value before the files upload event.
Try this way:
Server side:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string savePath = MapPath("~/Images/" + e.FileName);
// dont save file & return if condition not matched.
if (e.FileSize > 72000) // use same condition in client side code
{
return;
}
AjaxFileUpload1.SaveAs(savePath);
}
catch (Exception ex)
{
throw ex;
}
}
and on client side:
<script type="text/javascript">
function UploadComplete(sender, args) {
var filesize = args.get_fileSize();
var fileId = args.get_fileId();
var status = document.getElementById('AjaxFileUpload1_FileItemStatus_' + fileId);
var container = document.getElementById('AjaxFileUpload1_FileInfoContainer_' + fileId);
if (filesize > 72000) { // same condition used for server side
document.getElementById('lblStatus').innerText = "error";
if (status.innerText) {
status.innerText = " (Error)";
}
if (status.textContent) {
status.textContent = " (Error)";
}
container.style.color = 'Red';
}
}
</script>
<cc1:AjaxFileUpload ID="AjaxFileUpload1" AllowedFileTypes="jpg,jpeg" runat="server" MaximumNumberOfFiles="4" OnUploadComplete="AjaxFileUpload1_UploadComplete" OnClientUploadComplete="UploadComplete" />
Hope this helps!!
<script type="text/javascript">
$(".ajax__fileupload_dropzone").bind("drop", function () {
checkfilesize();
});
$(".ajax__fileupload_queueContainer").bind("click", function () {
checkfilesize();
});
$(".ajax__fileupload_uploadbutton").bind("mouseenter", function () {
checkfilesize();
});
function checkfilesize() {
var total_filesize_num = 0;
var myElements = $(".filesize");
if (myElements.length == 0) {
$(".ajax__fileupload_uploadbutton").css("visibility", "hidden");
return;
}
for (var i = 0; i < myElements.length; i++) {
var filesize = myElements.eq(i).html(); //$(".filesize").html();
total_filesize_num = total_filesize_num + filesize_tonum(filesize);
}
if (total_filesize_num > 5) {
$(".ajax__fileupload_uploadbutton").css("visibility", "hidden");
alert('Maximum file size is 5MB only! Please select another one.');
return;
} else {
$(".ajax__fileupload_uploadbutton").css("visibility", "visible");
}
}
function countsumfilesize() {
var sumfilesize = 0;
var myElements = $(".filesize");
for (var i = 0; i < myElements.length; i++) {
alert(myElements.eq(i).html());
}
}
function filesize_tonum(filesize) {
var filesize_num = 0;
if (filesize.indexOf("kb") > 0) {
var space = filesize.lastIndexOf(" ");
filesize_num = parseFloat("0." + filesize.substr(0, filesize.length - space + 1));
}
else if (filesize.indexOf("MB") > 0) {
var space = filesize.lastIndexOf(" ");
filesize_num = parseFloat(filesize.substr(0, filesize.length - space + 1));
}
return filesize_num;
}
</script>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUploadImage" runat="server" OnClientUploadComplete="uploadComplete" MaximumNumberOfFiles="1" AllowedFileTypes="gif,png,jpg,jpeg" onchange="checkfilesize(); return false;" />
See the code below:
public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
try
{
string savePath = MapPath("~/Uploads/" + Path.GetFileName(e.filename));
if (int.Parse(e.filesize) > 3000000)
{
return;
}
afuUpload.SaveAs(savePath);
}
catch (Exception ex)
{
throw ex;
}}
The idea is to prevent the file is uploaded to the server. In the proposed solution, when the flow code has reached afuUpload_UploadedComplete, the file was uploaded to server, but has not yet been recorded in the path you specify. For example, if the limit is 20 megabytes and the selected file is 22 megabytes, when the code reaches afuUpload_UploadedComplete, 22 Megabytes already been uploaded to the server.
The solution sought is that the validation is done on the client side (JavaScript) and that prevents the code arrives to CodeBehind on the server.
In my case, I tried to OnClientUploadComplete generating an exception when the file size limit is exceeded, but it did not work and the code is still reaching the CodeBehind. The other problem is that when the exception occurs, the JavaScript function OnClientUploadError is not firing to intercept the exception generated in OnClientUploadComplete function.
Controller
[HttpPost]
public ActionResult Create(string Album, Photo photo, IEnumerable<HttpPostedFileBase> files, DateTime? datec, string NewAlbum = null)
{
.....
foreach (var file in files)
{
decimal sum = file.ContentLength / 1048;
if (sum > 4000)
{
errorlist2 += "Sorry " + file.FileName + " has exceeded its file limit off 4 MB <br/>";
}
}
if (errorlist2 != "")
{
ViewBag.Error = errorlist2;
return View(photo);
}
// we dont want put the message in the loop it will come out on first max limit , rather find all files in excess, then we can pass the message
//also make sure your web config is set for a limit on max size
//using the normal html multi uploaded
// <input type="file" name="files" id="files" required multiple="multiple" accept=".jpg, .png, .gif" size="4" />

Validation with ajax AutoCompleteExtender

I have a TextBox with AutoCompleteExtenderwhen the person starts typing in the TextBox List with City name Appear .This works fine but now I want to validate that if they just type in a textbox and don't select one from the list that it validates that City Is Not Exist In database.
I want to validate it Using Ajax And Without PostBack Before Final Submit of form.
Add new js file with content below and add add reference on it to ToolkitScriptManager's Scrips collection:
Type.registerNamespace('Sjax');
Sjax.XMLHttpSyncExecutor = function () {
Sjax.XMLHttpSyncExecutor.initializeBase(this);
this._started = false;
this._responseAvailable = false;
this._onReceiveHandler = null;
this._xmlHttpRequest = null;
this.get_aborted = function () {
//Parameter validation code removed here...
return false;
}
this.get_responseAvailable = function () {
//Parameter validation code removed here...
return this._responseAvailable;
}
this.get_responseData = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.responseText;
}
this.get_started = function () {
//Parameter validation code removed here...
return this._started;
}
this.get_statusCode = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.status;
}
this.get_statusText = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.statusText;
}
this.get_xml = function () {
//Code removed
}
this.executeRequest = function () {
//Parameter validation code removed here...
var webRequest = this.get_webRequest();
if (webRequest === null) {
throw Error.invalidOperation(Sys.Res.nullWebRequest);
}
var body = webRequest.get_body();
var headers = webRequest.get_headers();
var verb = webRequest.get_httpVerb();
var xmlHttpRequest = new XMLHttpRequest();
this._onReceiveHandler = Function.createCallback(this._onReadyStateChange, { sender: this });
this._started = true;
xmlHttpRequest.onreadystatechange = this._onReceiveHandler;
xmlHttpRequest.open(verb, webRequest.getResolvedUrl(), false); // False to call Synchronously
if (headers) {
for (var header in headers) {
var val = headers[header];
if (typeof (val) !== "function") {
xmlHttpRequest.setRequestHeader(header, val);
}
}
}
if (verb.toLowerCase() === "post") {
if ((headers === null) || !headers['Content-Type']) {
xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
if (!body) {
body = '';
}
}
this._started = true;
this._xmlHttpRequest = xmlHttpRequest;
xmlHttpRequest.send(body);
}
this.getAllResponseHeaders = function () {
//Parameter validation code removed here...
return this._xmlHttpRequest.getAllResponseHeaders();
}
this.getResponseHeader = function (header) {
//Parameter validation code removed here...
return this._xmlHttpRequest.getResponseHeader(header);
}
this._onReadyStateChange = function (e, args) {
var executor = args.sender;
if (executor._xmlHttpRequest && executor._xmlHttpRequest.readyState === 4) {
//Validation code removed here...
executor._responseAvailable = true;
executor._xmlHttpRequest.onreadystatechange = Function.emptyMethod;
executor._onReceiveHandler = null;
executor._started = false;
var webRequest = executor.get_webRequest();
webRequest.completed(Sys.EventArgs.Empty);
//Once the completed callback handler has processed the data it needs from the XML HTTP request we can clean up
executor._xmlHttpRequest = null;
}
}
}
Sjax.XMLHttpSyncExecutor.registerClass('Sjax.XMLHttpSyncExecutor', Sys.Net.WebRequestExecutor);
On a page:
<ajaxToolkit:ToolkitScriptManager runat="server" ID="ScriptManager1">
<Scripts>
<asp:ScriptReference Path="~/XMLHttpSyncExecutor.js" />
</Scripts>
</ajaxToolkit:ToolkitScriptManager>
Then, add CustomValidator for target TextBox and use function below for client validation:
<asp:TextBox runat="server" ID="myTextBox" Width="300" autocomplete="off" />
<asp:CustomValidator runat="server" ID="myTbCustomValidator" ControlToValidate="myTextBox"
Text="*" Display="Dynamic" ValidateEmptyText="false" ClientValidationFunction="validateTextBox"
OnServerValidate="ValidateTextBox" />
function validateTextBox(sender, args) {
if (args.Value.length > 0) {
var extender = $find("AutoCompleteEx"); // AutoComplete extender's BehaviorID
if (extender._completionListElement) {
var children = extender._completionListElement.childNodes;
var length = extender._completionListElement.childNodes.length;
for (var i = 0; i < length; i++) {
if (children[i].innerHTML == args.Value) {
args.IsValid = true;
return;
}
}
}
var request = new Sys.Net.WebRequest();
request.set_url('<%= ResolveClientUrl("~/AutoComplete/AutoComplete.asmx/Validate") %>');
var body = Sys.Serialization.JavaScriptSerializer.serialize({ value: args.Value });
request.set_body(body);
request.set_httpVerb("POST");
request.get_headers()["Content-Type"] = "application/json; encoding=utf-8";
request.add_completed(function (eventArgs) {
var result = Sys.Serialization.JavaScriptSerializer.deserialize(eventArgs.get_responseData());
args.IsValid = result.d;
});
var executor = new Sjax.XMLHttpSyncExecutor();
request.set_executor(executor);
request.invoke();
}
}
The main idea of code above is to check suggested items at first for entered text and if there aren't any concidence then to do synchronous AJAX call to Validate method of web service or page method. That method should have such signature: public bool Validate(string value)
P.S. Code for XMLHttpSyncExecutor taken here: Using Synchronous ASP.Net AJAX Web Service Calls and Scriptaculous to Test your JavaScript

Page Got Postback in OnClientClick Return False

I am working in C#.Net. i am having an asp button..
<asp:Button ID="btnSubmitData" ToolTip="Show" runat="server" Text="SHOW" CausesValidation="false"
OnClientClick="return FindSelectedItems();" OnClick="btnShow_Click" />
The function called in OnClientClick is,
function FindSelectedItems() {
var sender = document.getElementById('lstMultipleValues');
var cblstTable = document.getElementById(sender.id);
var checkBoxPrefix = sender.id + "_";
var noOfOptions = cblstTable.rows.length;
var selectedText = "";
var total = 0;
for (i = 0; i < noOfOptions; ++i) {
if (document.getElementById(checkBoxPrefix + i).checked) {
total += 1;
if (selectedText == "")
selectedText = document.getElementById
(checkBoxPrefix + i).parentNode.innerText;
else
selectedText = selectedText + "," +
document.getElementById(checkBoxPrefix + i).parentNode.innerText;
}
}
var hifMet1 = document.getElementById('<%=hifMet1.ClientID%>');
hifMet1.value = selectedText;
if (total == 0) {
var panel = document.getElementById('<%=pnlOk.ClientID%>');
document.getElementById('<%=pnlOk.ClientID%>').style.display = 'block';
var Label1 = document.getElementById('<%=Label3.ClientID%>');
Label1.innerHTML = "Atleast one metric should be selected.";
var btnLoc = document.getElementById('<%=btnLoc.ClientID%>');
btnLoc.disabled = true;
var btnProd = document.getElementById('<%=btnProd.ClientID%>');
btnProd.disabled = true;
var btnLastYear = document.getElementById('<%=btnLastYear.ClientID%>');
btnLastYear.disabled = true;
return false;
}
else if (total > 2) {
var panel = document.getElementById('<%=pnlOk.ClientID%>');
document.getElementById('<%=pnlOk.ClientID%>').style.display = 'block';
var Label1 = document.getElementById('<%=Label3.ClientID%>');
Label1.innerHTML = "Only two metrics can be compared.";
var btnLoc = document.getElementById('<%=btnLoc.ClientID%>');
btnLoc.disabled = true;
var btnProd = document.getElementById('<%=btnProd.ClientID%>');
btnProd.disabled = true;
var btnLastYear = document.getElementById('<%=btnLastYear.ClientID%>');
btnLastYear.disabled = true;
return false;
}
else {
return true;
}
}
Once i click the SHOW Button, i need to do a validation to check at least one checkbox should get checked in checkbox list. That alert message i am getting (i.e) "Atleast one metric should be selected". But after this part, the page gets reloaded.
I want to avoid the page refresh at this point. What should i do here.?
One way is to hook your validation function into the proper ASP .Net validation lifecycle by using a CustomValidator control and a client validation function.
With a few minor changes you can turn your JavaScript code into a client validation function.
Full example here.
Relevant Snippets
<script language="javascript">
function ClientValidate(source, arguments)
{
// Your code would go here, and set the IsValid property of arguments instead
// of returning true/false
if (arguments.Value % 2 == 0 ){
arguments.IsValid = true;
} else {
arguments.IsValid = false;
}
}
</script>
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
Client validation should always be double-checked with server validation; using a CustomValidator with both client/server validation functions is a good way to accomplish this.
Remove script
else {
return true;
}
part from script and call function like this
OnClientClick="javascript:return FindSelectedItems();"
This work for me.

Why my yui datatable within an updatepanel disappears after postback?

I got my YUI datatable rendered with my json datasource inside an updatepanel... If i click a button within that updatepanel causes postback and my yui datatable disappears
Why yui datatable within an updatepanel disappears after postback?
EDIT:
I am rendering YUI Datatable once again after each post back which is not a form submit... I know it is a bad practice...
What can be done for this.... Any suggestion.....
if (!IsPostBack)
{
GetEmployeeView();
}
public void GetEmployeeView()
{
DataTable dt = _employeeController.GetEmployeeView().Tables[0];
HfJsonString.Value = GetJSONString(dt);
Page.ClientScript.RegisterStartupScript(Page.GetType(), "json",
"EmployeeDatatable('" + HfJsonString.Value + "');", true);
}
When i click any button in that page it causes postback and i have to
regenerate YUI Datatable once again with the hiddenfield value containing
json string..
protected void LbCancel_Click(object sender, EventArgs e)
{
HfId.Value = "";
HfDesigId.Value = "";
ScriptManager.RegisterClientScriptBlock(LbCancel, typeof(LinkButton),
"cancel", "EmployeeDatatable('" + HfJsonString.Value + "');, true);
}
My javascript:
function EmployeeDatatable(HfJsonValue){
var myColumnDefs = [
{key:"Identity_No", label:"Id", width:50, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Emp_Name", label:"EmployeeName", width:150, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Address", label:"Address", width:200, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"Desig_Name", label:"Category", width:200, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC}},
{key:"", formatter:"checkbox"}
];
var jsonObj=eval('(' + HfJsonValue + ')');
var target = "datatable";
var hfId = "ctl00_ContentPlaceHolder1_HfId";
generateDatatable(target,jsonObj,myColumnDefs,hfId)
}
function generateDatatable(target,jsonObj,myColumnDefs,hfId){
var root;
for(key in jsonObj){
root = key; break;
}
var rootId = "id";
if(jsonObj[root].length>0){
for(key in jsonObj[root][0]){
rootId = key; break;
}
}
YAHOO.example.DynamicData = function() {
var myPaginator = new YAHOO.widget.Paginator({
rowsPerPage: 10,
template: YAHOO.widget.Paginator.TEMPLATE_ROWS_PER_PAGE,
rowsPerPageOptions: [10,25,50,100],
pageLinks: 10 });
// DataSource instance
var myDataSource = new YAHOO.util.DataSource(jsonObj);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {resultsList: root,fields:new Array()};
myDataSource.responseSchema.fields[0]=rootId;
for(var i=0;i<myColumnDefs.length;i++){
myDataSource.responseSchema.fields[i+1] = myColumnDefs[i].key;
}
// DataTable configuration
var myConfigs = {
sortedBy : {key:myDataSource.responseSchema.fields[1], dir:YAHOO.widget.DataTable.CLASS_ASC}, // Sets UI initial sort arrow
paginator : myPaginator
};
// DataTable instance
var myDataTable = new YAHOO.widget.DataTable(target, myColumnDefs, myDataSource, myConfigs);
myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
myDataTable.subscribe("checkboxClickEvent", function(oArgs){
var hidObj = document.getElementById(hfId);
var elCheckbox = oArgs.target;
var oRecord = this.getRecord(elCheckbox);
var id=oRecord.getData(rootId);
if(elCheckbox.checked){
if(hidObj.value == ""){
hidObj.value = id;
}
else{
hidObj.value += "," + id;
}
}
else{
hidObj.value = removeIdFromArray(""+hfId,id);
}
});
myPaginator.subscribe("changeRequest", function (){
if(document.getElementById(hfId).value != "")
{
if(document.getElementById("ConfirmationPanel").style.display=='block')
{
document.getElementById("ConfirmationPanel").style.display='none';
}
document.getElementById(hfId).value="";
}
return true;
});
myDataTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
oPayload.totalRecords = oResponse.meta.totalRecords;
return oPayload;
}
return {
ds: myDataSource,
dt: myDataTable
};
}();
}
Hai guys,
I got an answer for my qusetion.... Its my postback that caused the problem and i solved it by making an ajax call using ajax enabled WCF Service in my web application... Everything works fine now....
Anything you are generating client side will have to be regenerated after every page refresh (and after every partial page refresh, if that part contains client-side generated html).
Because the YUI datatable gets its data on the client, you will have to render it again each time you replace that section of html.

Resources