Passing values to Javascript from code behind asp.net using Webmethod - javascript

I'm trying to add values queried from a DB into a google charts bar chart. After googling around, I tried by making a web method.
First I made a class:
public class ChartDetails
{
public string value_type { get; set; }
public float threshold { get; set; }
}
Then the web method (not connected to DB yet)
[WebMethod]
public static List<ChartDetails> GetChartData()
{
List<ChartDetails> dataList = new List<ChartDetails>();
ChartDetails c1 = new ChartDetails();
c1.threshold = 56;
c1.value_type = "Observed";
ChartDetails c2 = new ChartDetails();
c2.threshold = 33;
c2.value_type = "Forecast";
dataList.Add(c1);
dataList.Add(c2);
return dataList;
}
My script is added in the same form tag as the div with id="chartdiv":
script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'Page.aspx/GetChartData',
data: '{}',
success: function (response) {
drawchart(response.d); // calling method
},
error: function () {
alert("Error loading data! Please try again.");
}
});
})
function drawchart(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Type of value');
data.addColumn('float', 'Value');
for (var i = 0; i < dataValues.length; i++)
{
data.addRow([dataValues[i].value_type, dataValues[i].threshold] );
}
var chart = new google.visualization.ColumnChart(document.getElementById('chartdiv'));
chart.draw(data,
{
title: "Show Google Chart in Asp.net",
position: "top",
fontsize: "14px",
chartArea: { width: '50%' },
});
}
</script>
When I run the page it doesn't even load it. As if the web method is not called at all. Clearly I'm missing something that I can't identify. I've also seen solutions of this type so I'll be trying that next. But it would be nice to figure out why this isn't working out yet.

Related

Parameter Data Null Ajax to MVC Controller

Originally, I was passing one parameter to my MVC Controller via Ajax and it was working correctly. The parameter data was being received without any problems. However, I now need to pass an extra parameter and when I do this, neither parameter is sending data to the Controller? Thanks!
Ajax Code:
function uploadFile() {
var fileData = new FormData($(form1)[0]); //THIS IS A FILE UPLOAD
var details = JSON.stringify(markers); //MARKERS IS AN ARRAY
$.ajax({
url: '../Home/FilePost',
type: 'Post',
success: function (result) {
var newWindow = window.open('LasView?fileName=' + result, "", "new window");
},
error: function (xhr, status, error) {
alert(xhr.responseText);
},
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
// TODO...
}
return myXhr;
},
error: function () { },
data: { filePost: fileData, googleMarkers: details },
cache: false,
contentType: false,
processData: false
});
}
My Controller:
[HttpPost]
public string LasPost(HttpPostedFileBase filePost, string googleMarkers){
return something;
}
My Array:
var markerObject = {
lat: marker.position.lat(),
lng: marker.position.lng()
};
markers.push(markerObject);
You cannot mix FormData and objects. You must .append() each name/value pair to the FormData instance.
Because you stringified your array, and are binding to a string googleMarkers parameter, then your code would need to be
function uploadFile() {
var fileData = new FormData($(form1)[0]); //THIS IS A FILE UPLOAD
var details = JSON.stringify(markers); //MARKERS IS AN ARRAY
fileData.append('googleMarkers', details); // append the name/value pair
$.ajax({
....
data: fileData, // send only the FormData instance
....
});
})
However you should be taking advantage of MVC's model binding features and posting data which binds to a model representing your coordinates, for example
public class Coordinate
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
and the POST method would then be
[HttpPost]
public string LasPost(HttpPostedFileBase filePost, IEnumerable<Coordinate> googleMarkers)
and to send that data
var fileData = new FormData($(form1)[0]);
for(var i = 0; i < markers.length; i++)
{
fileData.append('[' + i + '].Latitude', markers[i].lat);
fileData.append('[' + i + '].Longitude', markers[i].lng);
}
$.ajax({
....
data: fileData,
....
});

FormData Values in Razor HTML page, getting in C# Method

I have following input element in razor view page
<input type="file" id="uploadFile" name="FileUpload" multiple="multiple" />
using following script I'm binding data to this ForData
$('#uploadFile').on('change', function()
{
var fd = new FormData();
var files = $('#uploadFile')[0].files;
for (var i = 0; i < files.length; i++)
{
if (files[i].size < 5242880)
{
fd.append("myFiles", files[i])
}
}
});
I'm trying to get these files in C# method like following
[HttpPost]
public ActionResult SomeAction(ModelClass model)
{
var attchaedfiles = System.Web.HttpContext.Current.Request.Files["myFiles"];
for (int i = 0; i < attchaedfiles.Count; i++)
{
if (!string.IsNullOrEmpty(attchaedfiles[i].FileName))
{
....
}
}
}
but here I'm getting folllowing errors
Operator '<' cannot be applied to operands of type 'int' and 'method
group'
Cannot apply indexing with [] to an expression of type
'System.Web.HttpPostedFile'
In your ajax script, make sure you include these:
$.ajax({
url: yourUrl,
type: 'POST',
// Needed for FormData submit
processData: false,
// Needed for FormData submit
contentType: false,
data: fd,
dataType: 'json',
success: function () {
// Success things
},
error: function () {
// Error things
},
complete: function () {
// Complete things
}
});
And that your form code includes enctype = "multipart/form-data":
#using (Html.BeginForm(null, null, FormMethod.Post, new { #action = YourAction, id = "your_id", enctype = "multipart/form-data" }))
Try the following approach that checks possible conditions regarding to file uploads:
Model:
public class ExperimentViewModel
{
public int Id { get; set; }
[DataType(DataType.Upload)]
public IEnumerable<HttpPostedFileBase> FileUpload { get; set; }
//other properties
}
Controller:
if (model.FileUpload != null)
{
if (model.FileUpload.Count() > 0)
{
foreach (var upload in model.FileUpload)
{
if (upload != null && upload.ContentLength > 0)
{
//your stuff
}
}
}
}
You can also look at my answer on How to display images in MVC.

How to print receipt without print dialog box in client side

I want print receipt in client side without print dialog box, i am using mvc this is my solution to achieve my problem.
EPSON printer was installed in my system.This solution is working when host in my local iis but its not work when host in server and accessing from my local system getting "An error occurred while processing your request" error. In server no printer is installed.
$.ajax({
type: "POST",
url: '../Service/print',
cache: false,
data: { iprintData: printData, iprinterName: sPrinterName },
success: function (data) {
// alert('print Send Successfully');
},
error: function (ex) {
alert(ex.responseText);
// alert('error while Seding print');
}
});
this is my code in controller
public JsonResult print(string iprintData, string iprinterName)
{
Boolean bflag = false;
System.Web.HttpContext.Current.Session["_printData"] = iprintData;
PrintDocument printDocument = new PrintDocument();
printDocument.PrintController = new StandardPrintController();
printDocument.PrintPage += PrintDocumentOnPrintPage;
printDocument.PrinterSettings.PrinterName = iprinterName;
//printFont = new System.Drawing.Font("Arial", 10);
printDocument.Print();
bflag = true;
return Json(bflag, JsonRequestBehavior.AllowGet);
}
public static Image resizeImage(Image image, int new_height, int new_width)
{
Bitmap new_image = new Bitmap(new_height, new_width);
Graphics g = Graphics.FromImage((Image)new_image);
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(image, 0, 0, new_width, new_height);
return new_image;
}
private void PrintDocumentOnPrintPage(object sender, PrintPageEventArgs e)
{
string printstring = System.Web.HttpContext.Current.Session["_printData"].ToString();
string path = HttpContext.Server.MapPath("~/content/Images/logo.png");
System.Drawing.Image img = Image.FromFile(path);
//img = resizeImage(img, 80, 60);
e.Graphics.DrawImage(img, 6, 100);
e.Graphics.DrawString(printstring, new System.Drawing.Font("ronnia", 9), Brushes.Black, 10, 150);
}
can any one help me from this ?
first you have to write windows service that contain HttpListener.
write your printing code inside the service
Install the service in client machine
call that service using ajax like below.
function PrintReceipt() {
var PrintData = JSON.parse($("#receiptData").html())
if (PrintData.length > 0) {
$.ajax({
type: "POST",
url: "http://localhost:41963/printOrder",
data: JSON.stringify({ "PrintData": PrintData }), //reciept data
crossDomain: true,
success: function (response) {
},
error: function () {
}
});
}
}
set System.Drawing.dll property
Copy Local=true

MVC DropDownList selection changed not firing Ajax

I am new to mvc and have been doing lots of looking, but I can't figure out why this isn't working.
I have the following View code:
$(function() {
$("#ddlNumberOfRecords").change(function() {
var numberOfRecords = $("#ddlNumberOfRecords").val();
$.ajax({
type: "POST",
url: '#Url.Action("NumberOfRecordsChanged")',
data: { numberOfRecords: numberOfRecords },
success: function(returndata) {
if (!returndata.ok) {
window.alert(' error : ' + returndata.message);
} else {
$('#Grid').html(returndata);
}
}
});
});
});
#Html.DropDownList("ddlNumberOfRecords", Model.NumberOfRecordsSelectList)
Can someone tell me what is wrong with that? Also, is there a way to debug that javascript? I put breakpoints on there, but they never load.
EDIT: This is my Action. There is no real content yet because I am just trying to get it to work at this point. But I have a breakpoint and it never gets hit.
[HttpPost]
public ActionResult NumberOfRecordsChanged(int numberOfRecords)
{
return null;
}
With everything you shown the code works 100%. I made a mock up to prove just that.
Controller
public ActionResult Index()
{
ViewModel model = new ViewModel
{
NumberOfRecordsSelectList = new List<SelectListItem>
{
new SelectListItem
{
Selected = false,
Text = "one",
Value = "1",
},
new SelectListItem
{
Selected = false,
Text = "two",
Value = "2",
},
}
};
return View(model);
}
[HttpPost]
public ActionResult NumberOfRecordsChanged(int numberOfRecords)
{
return null;
}
View
#model MvcApplication1.Models.ViewModel
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#ddlNumberOfRecords").change(function() {
var numberOfRecords = $("#ddlNumberOfRecords").val();
$.ajax({
type: "POST",
url: '#Url.Action("NumberOfRecordsChanged")',
data: { numberOfRecords: numberOfRecords },
success: function (returndata) {
//No return data proviced
//if (!returndata.ok) {
// window.alert(' error : ' + returndata.message);
//} else {
// $('#Grid').html(returndata);
//}
}
});
});
});
</script>
#Html.DropDownList("ddlNumberOfRecords", Model.NumberOfRecordsSelectList)
If you are getting another error than please share how you are creating your list items, what the error is, and any other details relevant to the problem. Thanks.
It seems you're trying to pass over the number of items in the dropdown but are in fact sending over the selected item's value.
If so, this...
var numberOfRecords = $("#ddlNumberOfRecords").val();
Should be this...
var numberOfRecords = $("#ddlNumberOfRecords option").size();

Problems updating database with Jquery.Ajax

I am working on a website and would like to be able to update a field on a database table when a div is clicked. I found some example code right here on stack but for some reason it won't work, even though it was accepted. I am using C# ASP.NET MVC Razor.
My JavaScript function is as follows:
function toggleContent(id, instID) {
var doc = document.getElementsByClassName("messageContent")[id];
$(doc).slideToggle();
$.ajax({
type: 'POST',
url: "#Url.Content('/Messages/MarkSeen/')",
data: {
instanceID : instID
},
dataType: 'json'
});
}
And my JsonResult is as follows:
[HttpPost]
public JsonResult MarkSeen(int instanceID)
{
var markSeen = db.MessageInstances.First(mi => mi.MessageInstanceId == instanceID);
if (markSeen.RegisteredPerson.PersonId == CurrentUser.PersonId)
{
markSeen.Seen = true;
db.SaveChanges();
return Json(true);
}
return Json(false);
}
I'm not sure where your code fails, so I posted complete working code
If you are using the ApiController, please try the following updates to make your code works:
1. add route to WebApiConfig.cs
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
2. javascript
$.ajax({
type: "POST",
url: "#Url.Content("/api/lab/MarkSeen")",
data: { "instanceID": instID },
dataType: 'json',
success: function (data) { alert(data)},
error: function () { alert('error'); }
});
3. Add model to match the json from ajax request:
public class labModel
{
public int instanceID { get; set; }
}
4. Controller:
[System.Web.Mvc.HttpPost]
public JsonResult<bool> MarkSeen(labModel data)
{
return Json(true);
}

Categories

Resources