ASP.NET: How to update client-side from server side? - asp.net

I want to update a label on client side from server side while the function is still under execution at server side. How can I achieve this?
Here's the code snippet:
protected void Button1_Click(object sender, EventArgs e)
{
string Result = "Success";
if (Result == "Success")
{
Label1.Text = "Plan mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Packing date mst Started";
}
if (Result == "Success")
{
Label1.Text = "Packing date mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Etd mst Started";
}
if (Result == "Success")
{
Label1.Text = "Etd mst Completed";
Thread.Sleep(2000); //Some functionality here
Label1.Text = "Inner box mst Started";
}
}
I want all changes in label1.text to be reflected on client side, while function is still under execution.
Please help!!!

Direct communication with the Front End from inside that method is going to be hard. Here's how I'd do it.
1) Split "Plan mst", "Packing date mst", "Etd mst", and "Inner box mst" into 4 separate functions.
2) Have the button click event on the page fire a JavaScript function to hit each of the 4 methods, one after the other, via AJAX. Make up a new ASPX page for each function ("InnerBox.aspx", etc). If you have jquery, it would look something like this:
$("#SubmitButton").click(function () {
DoPlanMst();
});
function DoPlanMst(argumentObj) {
SetLabel("Plan MST Started");
$.ajax({
url: "PlanMst.aspx",
type: "POST",
data: argumentObj, // your post params
success: function () {
SetLabel("Plan MST Completed");
DoPackingDateMst();
}
});
}
function DoPackingDateMst(argumentObj) {
SetLabel("Packing Date MST Started");
$.ajax({
url: "PackingDate.aspx",
type: "POST",
data: argumentObj, // your post params
success: function () {
SetLabel("Packing Date MST Completed");
DoEtdMst();
}
});
}
function DoEtdMst(argumentObj) {
SetLabel("ETD MST Started");
$.ajax({
url: "EtdMst.aspx",
type: "POST",
data: argumentObj, // your post params
success: function () {
SetLabel("ETD MST Completed");
DoInnerBoxMst();
}
});
}
function DoInnerBoxMst(argumentObj) {
SetLabel("Inner Box MST Started");
$.ajax({
url: "InnerBoxMst.aspx",
type: "POST",
data: argumentObj, // your post params
success: function () {
SetLabel("Inner Box MST Completed");
}
});
}
function SetLabel(message) {
$("#Label1").val(message);
}
If you don't want 4 sep ASPX pages, that's fine. You can roll them into a single file called "ProcessMSTs.aspx" that looks for a query string param to determine the method in its code behind to call, while still passing in POST params.
EDIT: fixed a typo in the function names in the success function of the AJAX calls.

how are you calling this function from the browser.Is it an asynchronous call then you can manage that in client side it self. if it is an synchronous one then it will not be possible as your response to you request is still pending.
use this
Jquery Ajax post animation during ajax process?

Related

my action method returning {"success=true,message="work done"} ASP.net MVC 5

Here is my create action method. I want get alert form it when success is true.
public JsonResult Create(Student student ,HttpPostedFileBase img)
{
if (ModelState.IsValid)
{
if (img !=null)
{
var name = Path.GetFileNameWithoutExtension(img.FileName);
var ext = Path.GetExtension(img.FileName);
var filename = name + DateTime.Now.ToString("ddmmyyyff") + ext;
img.SaveAs(Server.MapPath("~/img/"+filename));
student.ImageName = filename;
student.Path = "~/img/" + filename;
}
db.Students.Add(student);
db.SaveChanges();
return Json(new { success = true, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
ViewBag.ClassID = new SelectList(db.Classes, "Id", "Name", student.ClassID);
return new JsonResult { Data = new { success = false, message = "data not saved" } };
}
Here is my ajax function :
function onsub(form) {
$.validations.unobtrusive.parse(form);
if (form.valid()) {
var ajaxConfig = {
type: "POST",
url: form.action,
data: new FormData(form),
success: function (response) {
if (response.success ) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
}
}
if ($(form).attr("enctype") == "multipart/form-data") {
ajaxConfig["contentType"] = false;
ajaxConfig["processData"] = false;
}
$.ajax(ajaxConfig);
}
return false;
}
How can I get an alert form it
without reloading the form. I also want to submit images and other files to create an action method.
This is the result that I get after submitting the form:
In your case you are calling Create action which returning the JSON Result and the same Json response is displayed in browser.
Their should be a View page from where you will call this method by using the Ajax call, then you will be able to see your alert message.

400 bad request, but there is nothing wrong with this page

I am using paged lists on my mvc application. I have tons of different pages that do this, but for SOME random reason, this one throws a 400 bad request error. I am almost positive the code is the same.
public ViewResult ManageWeapons(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "WeaponName_desc" : "";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var weapon = from s in db.Weapons
select s;
if (!String.IsNullOrEmpty(searchString))
{
weapon = weapon.Where(s => s.WeaponName.Contains(searchString));
}
switch (sortOrder)
{
case "WeaponName_desc":
weapon = weapon.OrderByDescending(s => s.WeaponName);
break;
default: // ascending
weapon = weapon.OrderBy(s => s.WeaponName);
break;
}
int pageSize = 25;
int pageNumber = (page ?? 1);
return View(weapon.ToPagedList(pageNumber, pageSize));
}
I invoke it as so, to sort a column
//This function updates a pagedList using Ajax
function getSorterWeapons(sortOrder, currentFilter) {
//alert($(this).val());
console.log("making it!");
$.ajax({
type: "GET",
url: '#Url.Action("ManageWeapons", "AdminTools")',
cache: false,
data: { sortOrder: sortOrder, currentFilter: currentFilter },
error: function () {
alert("An error occurred.");
},
success: function (data) {
$("#manageWeaponsBox").html(data);
console.log("success!");
alert(data);
}
});
}
I have set breakpoints on the server and it makes it through just fine. Nothing seems to be going wrong, but the client constantly outputs 400 error in console.
I am doing this EXACT same function for other tables in my database and it works fine. This one has me to wits end.
This one would have been rather obvious has it been in an HTML post. The problem is as simple as that I had an error in the view (from accidently adding a character). The c# function was executing fine and then the code was breaking in the view side, one of the pitfalls of debugging using ajax and mvc.

Export to excel not working from HttpHandler J-Query AJAX

im have a weird problem whereby my functionality of exporting to excel doesnt seem to work.
im using J-Query and AJAX to pass html data to a http handler which has some simple context.Response code which all seems fine. Anyway, heres my code:
// my hyperlink for user to click
Click Here to Export
my J-Query/AJAX code
<script type="text/javascript">
$(document).ready(function () {
$("#hyperLink").click(function (e) {
var result = $('#output').html();
var newRes = result.replace('\n', '');
$.ajax({
url: "ExportToExcelhandler.ashx",
data: { 'htmlData': newRes },
dataType: "json",
type: "POST",
success: function (data) {
alert(data);
}
});
});
});
</script>
and my handler:
public void ProcessRequest(HttpContext context)
{
string htmlStuff = context.Request["htmlData"];
string trimStart = "";
string trimEnd = "";
if (htmlStuff != null)
{
trimStart = htmlStuff.Substring(75, htmlStuff.Length - 75);
trimEnd = trimStart.Remove(trimStart.Length - 8, 8) + "";
}
string final= trimEnd;
context.Response.Clear();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", "attachment; filename=excelData.xls");
context.Response.ContentType = "application/vnd.ms-excel";
HttpResponse response = context.Response;
context.Response.Output.Write(finalHtmlData);
context.Response.Flush();
context.Response.End();
}
-- Granted, I'm doing some weird things with replace function in my J-Query, and Substring and Remove in my handler; this is because i had to trim my html data so that only the table with the data inside it was included (caused error otherwise). The html data is just report data. So the html data is passed fine to the handler, and it goes through the ProcessRequest method fine, yet doesn't export to excel. Any help would be greatly appreciated, thanks.
Split this into two HTTP handlers, one to generate the Excel data and the second to retrieve the data and have a resource point at it, like this:
GenerateExcelDocument HTTP handler code:
public void ProcessRequest(HttpContext context)
{
string htmlStuff = context.Request["htmlData"];
var docIdentifier = this.GenerateExcelDocument(htmlStuff);
context.Response.ContentType = "text/plain";
context.Response.Write(docIdentifier.ToString("N"));
}
private Guid GenerateExcelDocument()
{
var identifier = Guid.NewGuid();
string trimStart = "";
string trimEnd = "";
if (htmlStuff != null)
{
trimStart = htmlStuff.Substring(75, htmlStuff.Length - 75);
trimEnd = trimStart.Remove(trimStart.Length - 8, 8) + "";
}
// Logic that generates your document and saves it using the identifier
// Can save to database, file system, etc.
return identifier;
}
Now you can call this HTTP handler, like this:
$(document).ready(function () {
$("#hyperLink").click(function (e) {
var result = $('#output').html();
var newRes = result.replace('\n', '');
$.ajax({
url: "GenerateExcelDocument.ashx",
data: { 'htmlData': newRes },
dataType: "json",
type: "POST",
success: function (result) {
window.location.href = '/RetrieveExcelDocument.ashx/' + result;
}
});
});
});
Note: The success callback is where you can hook up the HTML resource to the file retrieval from the server (think href of the anchor tag that worked without passing data to the handler before).
Finally, we need to build the retrieval HTTP handler logic to actually get the Excel document, based upon the identifier returned from the GenerateExcelDocument HTTP handler call, like this:
RetrieveExcelDocument HTTP handler code:
public void ProcessRequest(HttpContext context)
{
var identifier = new Guid(context.Request.Url.Segments[1]);
// Get Excel document content from database, file system, etc. here
var fileContent = GetExcelDocument(identifier);
context.Response.AddHeader("content-disposition",
"attachment; filename=excelData.xls");
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.OutputStream.Write(fileContent, 0, fileContent.Length);
}

stop old session list object to add up

what my code 'below' does is: the client javascript calls a webservice method which creates a generic list and then stores it into a session.
[WebMethod(EnableSession = true)]
public void SaveUserSelection(string slctdRooms, string slctdcst)
{
List<SelectRms> SelectR = Session["someinfo"] as List<SelectRms>;
if (SelectR == null)
{
SelectR = new List<SelectRms>();
Session["someinfo"] = SelectR;
}
SelectR.Add(new SelectRms { roomtype = slctdRooms, Roomcst = slctdcst });
}
I would then retreave the session to show the data in another page like this
List(SlctdRmWebSrv.SelectRms) SelctdRM = (List(SlctdRmWebSrv.SelectRms))Sessio["someinfo"];
if(SelctdRM != null)
{
repeater1.DataSource = SelctdRM;
repeater1.DataBind();
}
the problem is that every time I retreave the session to create a new list, the new data is added up to the old one. I want to have a situation where only the current data is displayed. I tried to clear the list, abandon the session, or clear the repeater before adding the new ones it did hehlp; easy there an easy way to get this done. many thanks
It sounds like you are calling SaveUserSelection multiple times from your javascript. If that's the case then only the very first time your list will be initialized.
Therefore, your list will keep adding stuff to the "old" list since the list has not been cleared or re-initialized .
You should probably put the initialization in a separate method (either on Page_Load or create a new WebMethod just to clear/initialized the list). For example, this is how it looks if you decide to put it on the Page_Load event:
Note: code no tested
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
Session["someinfo"] = new List<SelectRms>();
}
This is how it looks if you create a WebMethod:
[WebMethod(EnableSession = true)]
public void InitUserSelection()
{
Session["someinfo"] = new List<SelectRms>();
}
Call this method when you are ready to keep track of the user selection. Perhaps when your form initially loads (place this script at the bottom of the page):
$(document).ready(function() {
$.ajax({
type: "POST",
url: "PageName.aspx/InitUserSelection",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// After init you could use this method to do something else
}
});
});
So SaveUserSelection will look like this:
[WebMethod(EnableSession = true)]
public void SaveUserSelection(string slctdRooms, string slctdcst)
{
List<SelectRms> SelectR = Session["someinfo"] as List<SelectRms>;
if (SelectR != null)
SelectR.Add(new SelectRms { roomtype = slctdRooms, Roomcst = slctdcst });
}
And this is how your javascript looks like whenever your selection changes:
$.ajax({
type: "POST",
url: "PageName.aspx/SaveUserSelection",
data: "{'slctdRooms':'Value1','slctdcst':'Value2'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//your list was updated, you may do something afterwards
}
});
#Ulises. this is what I ma doing:
public List<SelectRms> GetUserContent()
{
List<SelectRms> SelectR=new List<SelectRms>();
Session["someinfo"] = SelectR;
return Session["someinfo"] as List<SelectRms>;
}
[WebMethod(EnableSession = true)]
public void SaveUserSelection(string slctdRooms, string slctdcst)
{
List<SelectRms> SelectR = GetUserContent();
SelectR.Add(new SelectRms { roomtype = slctdRooms, Roomcst = slctdcst });
}
But instead it returns a single (first) element of my list rather than the whole list, Any Help

Get data from aspx.cs page to aspx page

So I am using a jquery plug in that allows me to change the order of things in a list by dragging and dropping them.
So my goal is to be able to grab a list of my objects (AlertInfo) and using it in a javascript function.
I was able to use a json webservice call in a test project to pass the data to the page.
But we don't have a webservice page now so I tried to grab it from a aspx.cs page and it hasn't worked.
///Aspx page:
$.ajax({
type: "POST",
url: "~/Alerts/GetAlerts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = eval("(" + msg.d + ")");
jQuery.each(data, function (rec) {
AlertList[AlertList.length] = new objAlert(this.id, this.title, this.details, JSONDateSerializationFix(this.startdate), JSONDateSerializationFix(this.enddate));
UpdateDisplayList();
})
},
error: function (msg) {
alert("BRAD" + msg);
}
The issue is that the Alerts page in "URL /Alerts/GetAlerts" is Alerts.aspx.cs. I can't figure out if I can use this ajax command to call a method in a aspx.cs page.
//Code behind page aspx.cs
[WebMethod]
//[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetAlerts()
{
List<AlertInfo> list = AlertInfo.GetTestAlerts();
return new JavaScriptSerializer().Serialize(list);
}
public List<AlertInfo> GetAlertsList()
{
List<AlertInfo> list = AlertInfo.GetTestAlerts();
return list; ;
}
So I was hoping that I could load data into an asp control (dataList) and then grab the data
//code behind page
protected void Page_Load(object sender, EventArgs e)
{
dataListAlertList.DataSource = GetAlertsList();
dataListAlertList.DataBind();
}
public static List<AlertInfo> GetTestAlerts()
{
List<AlertInfo> list = new List<AlertInfo>();
list.Add(new AlertInfo("0", "Alert 1 Title", "Alert 1 Detail", "10/10/2010", "10/10/2011"));
list.Add(new AlertInfo("1", "Alert 2 Title", "Alert 2 Detail", "10/10/2010", "10/10/2011"));
return list;
}
//.aspx page
$(document).ready(function () {
var a1 = $("#dataListAlertList").val();
// do fun stuff now.
}
But I keep getting undefined....
Didn't need to preload. Ended up using the datalist and then changed how it was formatted. In the document ready function I grabbed the divs and applied the properties that needed to be set.

Resources