ajaxToolkit:AjaxFileUpload capture file description - c#

I'm trying to get the FileDescription asp:textbox to save into a db when the user clicks upload but it's coming back blank. what am I doing wrong?
this is in my upload.aspx file
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1"
ThrobberID="myThrobber" OnUploadComplete="AjaxFileUpload1_UploadComplete"
ContextKeys=""
AllowedFileTypes="jpg,jpeg,doc,xls"
MaximumNumberOfFiles="1"
runat="server"/>
</div>
File Description<asp:TextBox ID="FileDescription" Width="200" runat="server" ></asp:TextBox>
and this is in my upload.cs file
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
string sFileDescription = FileDescription.Text;
string filePath = "~/" + e.FileName;
AjaxFileUpload1.SaveAs(filePath);
}

Let's add individual descriptions for each uploaded file. To do this you need to download AjaxControlToolkit sources from Codeplex (here is a link to download: Latest toolkit sources and modify three files:
AjaxFileUpload.Item.pre.js
AjaxFileUpload.Control.pre.js
AjaxFileUpload.css
New content of the AjaxFileUpload.Item.pre.js file:
/// <reference path="../../../client/microsoftajax.extended/common/common.pre.js" />
Type.registerNamespace("Sys.Extended.UI.AjaxFileUpload");
Type.registerNamespace("AjaxFileUpload");
Sys.Extended.UI.AjaxFileUpload.Item = function (parentId, fileItem, onRemoveItem) {
this._deleteButton = null;
this._parentId = parentId;
this._inputElementValue = fileItem.value;
this._id = fileItem.id;
this._slices = fileItem.slices;
this._sliceIndex = 0;
this._fileInfoContainer = null;
this._fileStatusText = null;
this._isUploaded = false;
this._isUploading = false;
this._fileSize = 0;
this._fileName = "";
this._fileType = "";
this._bytesUploaded = 0;
this._fileComment = null;
this._ui = this.initUI(onRemoveItem);
};
Sys.Extended.UI.AjaxFileUpload.Item.prototype = {
initUI: function (onRemoveItem) {
var self = this, file = this._inputElementValue, utils = new Sys.Extended.UI.AjaxFileUpload.Utils(),
isHtml5Support = utils.checkHtml5BrowserSupport(),
// generate unique id for each item
id = this._id,
// create line item container
container = $common.createElementFromTemplate({
nodeName: "div",
properties: {
id: this._parentId + '_FileItemContainer_' + id,
},
cssClasses: ['ajax__fileupload_fileItemInfo']
}),
// create file info/status container
fileInfoContainer = $common.createElementFromTemplate({
nodeName: "div",
properties: {
id: this._parentId + '_FileInfoContainer_' + id,
style: {
display: 'inline-block'
}
}
}),
// create file info placeholder
fileInfoText = $common.createElementFromTemplate({
nodeName: "span",
properties: {
id: this._parentId + '_FileItemInfo_' + id
},
cssClasses: ['ajax__fileupload_fileItemInfo']
}),
// create file status placeholder
fileStatusText = $common.createElementFromTemplate({
nodeName: "span",
properties: {
id: this._parentId + '_FileItemStatus_' + id
},
cssClasses: ['uploadstatus']
}),
commentContainer = $common.createElementFromTemplate({
nodeName: 'div',
cssClasses: ['ajax__fileupload_fileItem_commentContainer']
}),
fileComment = $common.createElementFromTemplate({
nodeName: "input",
properties: {
id: this._parentId + '_FileItemComment_' + id,
type: 'text',
style: {
width: '100%'
}
},
cssClasses: ['ajax__fileupload_fileItem_commentInput']
}),
// init remove button
deleteButton = $common.createElementFromTemplate({
nodeName: "div",
properties: {
id: this._parentId + '_FileItemDeleteButton_' + id
},
cssClasses: ['removeButton']
});
this._fileName = utils.getFileName(file);
if (isHtml5Support) {
this._fileSize = file.size;
var fType = file.type ? '<span class="filetype">(' + file.type + ')</span>' : '';
fileInfoText.innerHTML = '<span class="filename">' + this._fileName + '</span> '
+ fType
+ ' - <span class="filesize">' + utils.sizeToString(file.size) + '</span> ';
this._fileType = file.type;
} else {
fileInfoText.innerHTML = '<span class="filename">' + this._fileName + '</span>';
this._fileType = utils.getFileType(file);
}
commentContainer.innerHTML = '<label class="ajax__fileupload_fileItem_commentLabel" for="' + this._parentId + '_FileItemComment_' + id + '">Description:</label>';
commentContainer.appendChild(fileComment);
fileInfoContainer.appendChild(fileInfoText);
fileInfoContainer.appendChild(fileStatusText);
fileInfoContainer.appendChild(commentContainer);
$common.setText(deleteButton, Sys.Extended.UI.Resources.AjaxFileUpload_Remove);
$addHandlers(deleteButton, {
'click': Function.createDelegate(this, function () {
onRemoveItem(self);
})
});
// build the line item
if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version <= 8) {
container.appendChild(deleteButton);
container.appendChild(fileInfoContainer);
}
else {
container.appendChild(fileInfoContainer);
container.appendChild(deleteButton);
}
this._fileInfoContainer = fileInfoContainer;
this._deleteButton = deleteButton;
this._fileStatusText = fileStatusText;
this._fileComment = fileComment;
return container;
},
setStatus: function (fileStatusText, text) {
$common.setText(this._fileStatusText, ' (' + text + ')');
this._fileInfoContainer.setAttribute('class', fileStatusText + 'State');
},
disabled: function (on) {
if (on)
this._deleteButton.disabled = this._fileComment.disabled = 'disabled';
else
this._deleteButton.disabled = this._fileComment.disabled = '';
},
hide: function () {
this._deleteButton.style.visibility = 'hidden';
this._fileComment.readOnly = true;
},
destroy: function () {
$common.removeElement(this._inputElementValue);
$common.removeElement(this._deleteButton);
$common.removeElement(this._fileComment);
$common.removeElement(this._ui);
},
get_inputElementValue: function () {
return this._inputElementValue;
},
appendNodeTo: function (parent) {
parent.appendChild(this._ui);
},
removeNodeFrom: function (parent) {
parent.removeChild(this._ui);
},
get_fileComment: function () {
return this._fileComment.value;
}
};
In this code added new class field _fileComment, new function get_fileComment and modified initUI, disabled, hide and destroy functions. After these changes, each file item will have individual textbox for file description.
After that, change a bit AjaxFileUpload.Control.pre.js file. Rewrite the doneAndUploadNextFile function as below:
doneAndUploadNextFile: function (fileItem) {
/// <summary>
/// Mark fileItem as uploaded, and upload next file in queue.
/// </summary>
/// <param name="fileItem">Uploaded File</param>
// send message to server to finalize this upload
var xhr = new XMLHttpRequest(),
self = this;
xhr.open("POST", "?contextKey="+ this._contextKey +"&done=1&guid=" + fileItem._id + "&comment=" + fileItem.get_fileComment(), true);
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
// Mark as done and invoke event handler
self.raiseUploadComplete(Sys.Serialization.JavaScriptSerializer.deserialize(xhr.responseText));
// Upload next file
self._processor.startUpload();
} else {
// finalizing is error. next file will not be uploaded.
self.setFileStatus(fileItem, 'error', Sys.Extended.UI.Resources.AjaxFileUpload_error);
self.raiseUploadError(xhr);
throw "error raising upload complete event and start new upload";
}
}
};
xhr.send(null);
}
And the last step is a AjaxFileUpload.css file. Change heigh css rile in .ajax__fileupload_fileItemInfo class definition and add three additional classes for description:
.ajax__fileupload_fileItemInfo {
line-height: 20px;
height: 44px;
margin-bottom: 2px;
overflow: hidden;
}
.ajax__fileupload_fileItem_commentContainer {
display: table;
width: 100%;
}
.ajax__fileupload_fileItem_commentLabel {
display: table-cell;
width: 1px;
white-space: nowrap;
padding-right: 5px;
}
.ajax__fileupload_fileItem_commentInput {
display: table-cell;
width: 100%;
}
After these changes rebuild toolkit solution and use custom dlls.
Now you can get posted description from query string in OnUploadComplete event handler: var comment = Request.QueryString["comment"];

Related

Blazor with JsRuntine Interop

I'm trying to invoke a javascript function in a Blazor component, but with no success.
The error is:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Could not find 'FullCalendarInterop.init' ('FullCalendarInterop' was undefined).
Error: Could not find 'FullCalendarInterop.init' ('FullCalendarInterop' was undefined).
at https://localhost:7065/_framework/blazor.webassembly.js:1:328
at Array.forEach ()
at a.findFunction (https://localhost:7065/_framework/blazor.webassembly.js:1:296)
at _ (https://localhost:7065/_framework/blazor.webassembly.js:1:2437)
at https://localhost:7065/_framework/blazor.webassembly.js:1:3325
at new Promise ()
Component structure:
Razor page:
#using Microsoft.JSInterop
#inject IJSRuntime JSRuntime
protected override async Task OnAfterRenderAsync(bool firstRender)
{
var options = new CalendarOptions
{
Id = Id,
DefaultView = View,
CalendarEvents = Events.Where(r => r.Status == CalendarEventStatus.Active).ToList()
};
var dotNetObjectReference = DotNetObjectReference.Create(this);
var fullCalendarInterop = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./Shared/InputCalendar.razor.js");
await fullCalendarInterop.InvokeVoidAsync("FullCalendarInterop.init", options, dotNetObjectReference);
// I already just tried^
// await JSRuntime.InvokeVoidAsync("FullCalendarInterop.init", options, DotNetObjectReference.Create(this));
await base.OnAfterRenderAsync(firstRender);}
Javascript
var FullCalendarInterop = function () {
return {
//main function to initiate the module
init: function (options, dotNetReference) {
var calendarEl = document.getElementById(options.id);
var calendar = new window.FullCalendar.Calendar(calendarEl, {
plugins: ['interaction', 'dayGrid', 'timeGrid', 'list'],
isRTL: window.KTUtil.isRTL(),
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
height: 800,
contentHeight: 750,
aspectRatio: 3, // see: https://fullcalendar.io/docs/aspectRatio
views: {
dayGridMonth: { buttonText: 'month' },
timeGridWeek: { buttonText: 'week' },
timeGridDay: { buttonText: 'day' },
listWeek: { buttonText: 'list' }
},
defaultView: options.defaultView,
defaultDate: options.defaultDate,
editable: true,
eventLimit: true, // allow "more" link when too many events
navLinks: true,
events: options.calendarEvents,
eventRender: function (info) {
var event = $(info.event);
var element = $(info.el);
var view = $(info.view);
if (info.event.extendedProps && info.event.extendedProps.description) {
if (element.hasClass('fc-day-grid-event')) {
element.data('content', info.event.extendedProps.description);
element.data('placement', 'top');
window.KTApp.initPopover(element);
} else if (element.hasClass('fc-time-grid-event')) {
element.find('.fc-title').append('<div class="fc-description">' + info.event.extendedProps.description + '</div>');
} else if (element.find('.fc-list-item-title').lenght !== 0) {
element.find('.fc-list-item-title').append('<div class="fc-description">' + info.event.extendedProps.description + '</div>');
}
}
element.find(".fc-bg").css("pointer-events", "none");
element.find(".fc-list-item-title.fc-widget-content").prepend(
"<span style='position: absolute; right: 5px;'>" +
"<button class='btn btn-icon btn-xs btn-circle btn-light' " +
"style='height: 16px; width: 16px;' id='calendar_del_" + event.id + "'>" +
"<i class='icon-xs text-dark-50 flaticon2-cross'></i></button></span>");
element.find(".fc-content").append("<span style='position: absolute; top: 5px; right: 5px;'>" +
"<button class='btn btn-icon btn-xs btn-circle btn-light' " +
"style='height: 16px; width: 16px;' id='calendar_del_" + event.id + "'>" +
"<i class='icon-xs text-dark-50 flaticon2-cross'></i></button></span>");
element.find("#calendar_del_" + event.id).click(function () {
var eventId = event[0]._def.defId;
var eventIdentifier = event[0]._def.extendedProps.identifier;
//Remove popover
removeContent(".popover.fade.show.bs-popover-top");
//$(".popover.fade.show.bs-popover-top").remove();
dotNetReference.invokeMethodAsync('CalendarEventDeleted', eventIdentifier);
//$("#candidate_calendar").fullCalendar('removeEvents', eventId);
});
},
viewSkeletonRender: function (info) {
var view = $(info.view);
var defaultView = view[0].type !== null ? view[0].type : "";
dotNetReference.invokeMethodAsync('SetDefaultView', defaultView);
//alert(defaultView);
}
});
calendar.render();
}
};
}
Modify your .JS file like so:
var FullCalendarInterop = function () {
return {
//main function to initiate the module
init: function (options, dotNetReference) {
... Trimmed for brevity ...
calendar.render();
}
};
}();
export { FullCalendarInterop };
I added (); to the end of your FullCalendarInterop function and then added the export. That should work for you.
As it says its a null reference error as you are not initializing JSmodule,
IJSObjectReference fullCalendarInterop;
fullCalendarInterop = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./Shared/InputCalendar.razor.js");

How do you move data from one cell in one row of a web grid to another cell in another row that is empty using jQuery?

I am kind of lost when it comes to jQuery sometimes, though I know there is a way! How do you update or move three cells data to another row based on the rows id to where the row is green (empty cells)? The row column ID name is "LocationID". MVC application using a web grid. What I am trying to do is when I check the row, use the drop-down that has the id, send the data to that row where the id exists populating the three empty cells in green with the current columnar data row that is checked. Any help would be greatly appreciated!
WebGrid below:
enter
<div id="content">
#webGrid.GetHtml(tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
//alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
htmlAttributes: new { #id = "webGrid" },
columns: webGrid.Columns(
webGrid.Column(header: "Actions", format:#<span class="link">
<!--Add Checkbox here-->
<!-- Note: We can add clickable rows as an option for user using a checkbox, one
selects the data move and the other move to selection. -->
#Html.CheckBoxFor(model => model.SelectedMoveIsChecked, new { #Class =
"SelectedMoveIsChecked", #id = "SelectedMoveIsChecked", #checked = false })
#Html.CheckBoxFor(model => model.SelectedMoveToChecked, new { #Class =
"SelectedMoveToChecked", #id = "SelectedMoveToChecked", #checked = false })
<!-- Html.CheckBox("isActive", false, item.isSelectdRow, true, new { id =
"CheckBoxSelectedBeginMove", Class = "CheckBoxIsSelected" })
Html.CheckBoxFor(Model.Input_Location, item.isSelectdRow, new { = "'SelectedRows'",
data_val = item.Location })
-->
<a class="Edit" href="javascript:;">Edit</a>
<a class="Clear" href="javascript:;">Clear</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</span>),
webGrid.Column(header: "Location", format: #<div>
<label id="LocationLbl" class="label">#item.Location</label>
<input id="Location" class="text" type="text" value="#item.Location" style="display:none"
/><br />
#Html.DropDownListFor(model => model.LocationAppended, Model.LocationAppended,
"Section/Location", new { IReadOnlyDictionary = "document.forms[0].submit();", #id =
"RowLocationDropDownList", #class = "RowLocationDropDownList", #visibility = "hidden",
#placeholder = "Location" })
</div>, style: "Location"),
webGrid.Column(header: "Section", format: #<div>
<label id="SectionLbl" class="label">#item.Section</label>
<input id="Section" class="text" type="text" value="#item.Section" style="display:none" />
</div>, style: "Section"),
webGrid.Column(header: "TrailerNumber", format: #<div>
<label id="TrailerNumberLbl" class="label">#item.TrailerNumber</label>
<input id="TrailerNumber" class="text" type="text" value="#item.TrailerNumber"
style="display:none" />
</div>, style: "TrailerNumber"),
webGrid.Column(header: "CarrierName", format: #<div>
<label id="CarrierNameLbl" class="label">#item.CarrierName</label>
<input id="CarrierName" class="text" type="text" value="#item.CarrierName"
style="display:none" />
</div>, style: "CarrierName"),
webGrid.Column(header: "LoadCommodityStatus", format: #<div>
<label id="LoadCommodityStatusLbl" class="label">#item.LoadCommodityStatus</label>
<input id="LoadCommodityStatus" class="text" type="text" value="#item.LoadCommodityStatus"
style="display:none" />
</div>, style: "LoadCommodityStatus"),
webGrid.Column(header: "DateLoaded", format: #<div>
<label id="DateLoadedLbl" class="label">#item.DateLoaded</label>
<input id="DateLoaded" class="text" type="text" value="#item.DateLoaded" style="display:none"
/>
</div>, style: "DateLoaded"),
webGrid.Column(header: "UserName", format: #<div>
<label id="UserNameLbl" class="label">#item.UserName</label>
<input id="UserName" class="text" type="text" value="#item.UserName" style="display:none" />
</div>, style: "UserName"),
webGrid.Column(header: "PlantLocation", format: #<div>
<label id="PlantLocationLbl" class="label">#item.PlantLocation</label>
<input id="PlantLocation" class="text" type="text" value="#item.PlantLocation"
style="display:none" />
</div>, style: "PlantLocation"),
webGrid.Column(header: "RowPageID", format: #<div>
<label id="LocationIDLbl" class="label">#item.LocationID</label>
</div>, style: "LocationID"))),
<div id="RowCountBpttom"><b>Records: #firstRecord - #lastRecord of
#webGrid.TotalRowCount</b></div>
</div>
<br />
<div class="WebGridTable">
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">
</script>
<script src="~/Scripts/YardDogAdmin.js"></script>
</body>
jQuery Below:
code here
enter
$('select.RowLocationDropDownList').attr('disabled', true);
$(".SelectedMoveIsChecked").change(function (i, row) {
$actualRowColorRed = $(row);
//When a value is selected in the dropdownlist box.
if ($(this).children("option:selected").val() != '') {
$("select.RowLocationDropDownList").change(function (i, row) {
$actualRowColorRed = $(row);
//Checks to see if the checkbox is checked, display the alert showing data and color the row red again.
/////// if ($('.SelectedMoveIsChecked').is(':checked') == true) {
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[0];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[1];
var RowLocation = ret[2];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
// var ConfirmStr = " <b>Are you sure, you want to move this row From: </b>" + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
// alert("Alert " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?"
// );
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
//Add new values to (TrailerNumber, CarrierName, LoadCommodityStatus, DateLoaded, UserName).
//Note: Get the UserName currently using the Yard Dog Application.
/// $('#webGrid').closest('tr').find('#TrailerNumber').val();
/// $("#webGrid tbody tr").each(function (i, row) {
// $('#webGrid tbody tr').find('#LocationID'.val(RowLocationIDNum); //= RowLocationIDNum).append('#TrailerNumber'.val(CurrentRowTrailerNumber));
$("body").on("change", "select.RowLocationDropDownList", function () {
// $("body").on("click", "#webGrid TBODY .Update", function () {
// $("#content").on("click", "#webGrid INPUT", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
span.html(input.val());
}
});
//// $('#webGrid tbody tr').find('#LocationID').val(RowLocationIDNum) = customer;
var RowExchange = $(RowLocationID).closest("tr");
var ToRow = {};
ToRow.LocationID = row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
/*
ToRow.LocationID = RowExchange.find('#LocationID').append(RowLocationID) ;
ToRow.UserName = RowExchange.find('.UserName').append(row.find(".UserName").find(".label").html());
ToRow.Location = RowExchange.find('.Location').append(row.find(".Location").find(".label").html());
ToRow.Section = RowExchange.find('.Section').append(row.find(".Section").find(".label").html());
ToRow.TrailerNumber = RowExchange.find('.TrailerNumber').append(ToRow.TrailerNumber);
ToRow.CarrierName = RowExchange.find('.CarrierName').val().append(ToRow.CarrierName);
ToRow.LoadCommodityStatus = RowExchange.find('.LoadCommodityStatus').append(ToRow.LoadCommodityStatus);
ToRow.DateLoaded = RowExchange.find('.DateLoaded').append(row.find(".DateLoaded").find(".label").html());
ToRow.PlantLocation = RowExchange.find('.PlantLocation').append(row.find(".PlantLocation").find(".label").html());
*/
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) +'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 777);
});
}
else {
confirm_value.value = "Cancel";
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
code here
Controller:
enter [HttpPost]
public ActionResult UpdateRowExchange(LocationData ToRow)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == ToRow.LocationID
select c).FirstOrDefault();
//Check for Duplicates.
///FindDuplicates(customer);
//HighlightDuplicate(webGrid);
//x => customer.TrailerNumber == x.TrailerNumber && x.TrailerNumber == customer.TrailerNumber //errases all data except the first cell TrailerNumber.
if (ToRow.UserName != null) updatedCustomer.UserName = ToRow.UserName.ToUpper();
else updatedCustomer.UserName = ToRow.UserName = null;
/*
if (customer.Location != null) updatedCustomer.Location = customer.Location.ToUpper();
else updatedCustomer.Location = customer.Location = null;
if (customer.Section != null) updatedCustomer.Section = customer.Section.ToUpper();
else updatedCustomer.Section = customer.Section = null;
*/
if (ToRow.TrailerNumber != null) updatedCustomer.TrailerNumber = ToRow.TrailerNumber.ToUpper();
else updatedCustomer.TrailerNumber = ToRow.TrailerNumber = null;
if (ToRow.CarrierName != null) updatedCustomer.CarrierName = ToRow.CarrierName.ToUpper();
else updatedCustomer.CarrierName = ToRow.CarrierName = null;
if (ToRow.LoadCommodityStatus != null) updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus.ToUpper();
else updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus = null;
if (ToRow.DateLoaded != null) updatedCustomer.DateLoaded = ToRow.DateLoaded.ToUpper();
else updatedCustomer.DateLoaded = ToRow.DateLoaded = null;
/*
if (customer.PlantLocation != null) updatedCustomer.PlantLocation = customer.PlantLocation.ToUpper();
else updatedCustomer.PlantLocation = customer.PlantLocation = null;
*/
//Create today's Date for a timestamp of inputs.
DateTime now = DateTime.Today;
ToRow.DateLoaded = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
updatedCustomer.DateLoaded = ToRow.DateLoaded;
entities.SaveChanges();
//Refresh(out, customer.ToString());
}
return new EmptyResult();
}
code here
Model below:
enter code here
namespace YardDog.Model
{
public class YardDogModel
{
ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
//Two Properties for DropDownList.
public List<LocationData> LocationDatas { get; set; }
//public List<LocationData> Location { get; set; }
public List<LocationData> TrailerNumber { get; set; }
public List<SelectListItem> PlantLocation { get; set; }
public List<SelectListItem> Location { get; set; }
public List<SelectListItem> LocationList { get; set; }
public List<SelectListItem> SectionList { get; set; }
public List<SelectListItem> LocationAppended { get; set; }
[Display(Name = "Name")]
public List<SelectListItem> Section { get; set; }
public List<SelectListItem> ListDuplicates { get; set; }
public List<SelectListItem> UserName { get; set; }
//Allow the data to be transfered (Backend into SQL Server).
[Required]
public string Input_Location { get; set; }
[Required]
public string Input_Section { get; set; }
public string Input_TrailerNumber { get; set; }
public string Input_CarrierName { get; set; }
public string Input_CommodityLoadStatus { get; set; }
[Required]
public string Input_PlantLocation { get; set; }
//YardDogModel YardDogDatas = new YardDogModel();
//string TrailerNumber = Input_TrailerNumber;
public bool SelectedMoveIsChecked { get; set; } = false;
public bool SelectedMoveToChecked { get; set; } = false;
public string LocationAppendedLbl { get; internal set; }
//public string LocationAppended { get; internal set; }
public string RowLocationDropDownList { get; set; }
public int RowLocationIDNum { get; set; }
}
}
JavaScript:
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[2];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[0];
var RowLocation = ret[1];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
$("body").on("change", "select.RowLocationDropDownList", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
span.html(input.val());
}
});
//Tell the row change to be where ID exists by ID Number (RowLocationIDNum).
var ToRow = {};
ToRow.LocationID = RowLocationIDNum; //row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
});
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 500);
});
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 500);
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
});
}
});

how to display Highcharts from database in C# .Net

I have seen this http://codepedia.info/chartjs-asp-net-create-pie-chart-with-database-calling-jquery-ajax-c/ link and followed every steps but dint get the output(i have used "public class cityPopulation") in code behind instead of asmx page will it be the error
</head>
<body>
<script>
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "aspchartjsdemo.aspx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
</script>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlyear" runat="server" >
<asp:ListItem>2010</asp:ListItem>
<asp:ListItem>2011</asp:ListItem>
<asp:ListItem>2012</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnCreatePieChart" runat="server" Text="Button" />
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
</div>
</form>
</body>
</html>
here is my Code Behind..Im Unable to Fetch the data from database.
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
using (NpgsqlConnection con = new NpgsqlConnection("Server=Localhost;Port=5432;User Id=postgres;Password=postgres;Database=database4;"))
{
string myQuery = "SELECT id_, city_name, population FROM tb_city_population WHERE year_of = #year";
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.CommandText = myQuery;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#year", pData[0]);
cmd.Connection = con;
con.Open();
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
cityPopulation cpData = new cityPopulation();
cpData.city_name = dr["city_name"].ToString();
cpData.population = Convert.ToInt32(dr["population"].ToString());
p.Add(cpData);
}
}
}
return p;
}
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
Any Help Highly appreciated..
This is how I build the Pie:
<div id="pieChart"></div>
<script type="text/javascript" src="highcharts.js"></script>
<script>
var myPieData = [ ['AAA', 34.03], ['BBB', 27.01], ['CCC', 18.77], ['DDD', 11.01], ['EEE', 5.91], ['FFF', 3.27] ];
chart = new Highcharts.Chart({
chart: {
renderTo: 'pieChart',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'My PieData'
},
tooltip: {
pointFormat: '<b>{point.percentage:.2f}%</b>',
percentageDecimals: 2
},
plotOptions: {
pie: {
allowPointSelect: false,
cursor: 'default',
dataLabels: {
enabled: false,
color: '#000000',
connectorColor: '#000000',
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';
}
}
}
},
series: [{
type: 'pie',
name: '',
data: myPieData
}]
});
</script>
The part you have to replace with your own data is [ ['Label A', 34.03], ['Label B', 27.01], ['Label C', 18.77], ['Label D', 11.01], ['Label E', 5.91], ['Label F', 3.27] ]
Of course the total value of all the data should be 100.00%
You can do that with a Literal or a string that is filled with content from code behind: var myPieData = [ <%= pieData %> ] or get it from an external source.
Depending on your localization settings, a numeric value can contain a "," instead of a "." (23,59 or 23.59). If your localization uses a "," you will have to replace that with a dot.
UPDATE
As requested an example of how to get a correct string that you can use to build the pie. This should get you started... Just make sure that population is in percentages, not absolute numbers.
public string getCityPopulation(List<string> pData)
{
StringBuilder sb = new StringBuilder();
string myQuery = "SELECT city_name, population FROM tb_city_population WHERE (year_of = #year)";
using (SqlConnection connection = new SqlConnection(Common.connectionString))
using (SqlCommand command = new SqlCommand(myQuery, connection))
{
command.Parameters.AddWithValue("#year", pData[0]);
try
{
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
sb.Append("[");
sb.Append("'" + dr["city_name"].ToString() + "'");
sb.Append(", ");
sb.Append(dr["population"].ToString().Replace(",", "."));
sb.Append("],");
}
}
}
catch
{
//error connecting\reading the database
}
}
return "[ " + sb.ToString().TrimEnd(',') + " ]";
}

Why my code is repeated in async upload file web api

In upload async file :
for example if i uploading 3 file Debug.WriteLine(info.FullName); and _db.Files.Add(New FileDto{FileName=info.Name}); repeated 50 time.means 50 record insert in database.
Why and how to avoid it?
what is my problem?
public Task<IEnumerable<FileDesc>> Post()
{
string folderName = "uploads";
string PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
if (Request.Content.IsMimeMultipartContent())
{
var streamProvider = new CustomMultipartFormDataStreamProvider(PATH);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
Debug.WriteLine(info.FullName);//************Repeated******
_db.Files.Add(New FileDto{FileName=info.Name});//************Repeated******
return new FileDesc(info.Name, rootUrl + "/" + folderName + "/" + info.Name, info.Length / 1024);
});
return fileInfo;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
[Update]
CustomMultipartFormDataStreamProvider :
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path)
: base(path)
{
}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";
return name.Replace("\"", string.Empty);
}
}
[Update]
$('#fileupload').fileupload({
dataType: "json",
url: "/media/upload",
limitConcurrentUploads: 1,
sequentialUploads: true,
progressInterval: 100,
maxChunkSize: 10000,
add: function (e, data) {
$('#filelistholder').removeClass('hide');
data.context = $('<div />').text(data.files[0].name).appendTo('#filelistholder');
$('<div class="progress progress-striped active"><div style="width: 0%;" class="progress-bar progress-bar-warning"></div></div>').appendTo(data.context);
$('#btnUploadAll').click(function () {
data.submit();
});
},
done: function (e, data) {
data.context.text(data.files[0].name + '... Completed');
$('<div class="progress progress-striped active"><div style="width: 100%;" class="progress-bar progress-bar-success"></div></div>').appendTo(data.context);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#overallbar').css('width', progress + '%');
},
progress: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
data.context.find('.progress-bar').css('width', progress + '%');
}
});
Your Debug.WriteLine is in the projection function of streamProvider.FileData.Select, so it is executed as many times as there are items in streamProvider.FileData.

How to customize Google charts from code using C#?

I am using google charts for my asp.net web application. I have successfully got the chart working in my application. But I want to know how to add animation, change the color of the column chart from code. In javascript I know it can be done using below option -
var options = {
width: 400,
height: 240,
title: 'Sample Data',
colors: ['#e0440e', '#f6c7b6'],
is3D:true
};
I tried calling the same in c# using string builder but chart itself doesnot load. Here is my code-
private void BindCourseChart()
{
//to bind course chart
DataTable dt = new DataTable();
try
{
dt = GetData_Course();
str.Append(#"<script type=text/javascript> google.load( *visualization*, *1*, {packages:[*corechart*],callback:drawChart});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Title');
data.addColumn('number', 'Users enrolled');
**//Here I am adding role=style for customizing**
data.addColumn({type: 'string', role: 'style'});
data.addRows(" + dt.Rows.Count + ");");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i] ["Title"].ToString() + "');");
str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["MenteeCount"].ToString() + ") ;");
}
str.Append(" var chart = new google.visualization.ColumnChart(document.getElementById('course_div'));");
str.Append(" chart.draw(data, {width: 650, height: 300, title: 'Course Enrollment', color:#0092CB,");
str.Append("hAxis: {title: 'Course Title', titleTextStyle: {color: 'green'}}");
str.Append("}); }");
str.Append("</script>");
lt_course.Text = str.ToString().TrimEnd(',').Replace('*', '"');
}
Can anyone help me in this regard how to add colors,or animation to column charts .
Thanks in advance
If interested, I made a Google Chart class awhile back that I've used in a few projects:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Google
{
/// <summary>
/// Summary description for GoogleChart
/// </summary>
public class GoogleChart
{
// Fields
private string data = "";
private string javascript;
// Properties
public string elementId { get; set; }
public int height { get; set; }
public string title { get; set; }
public int width { get; set; }
// ChartTypes
public enum ChartType
{
BarChart,
PieChart,
LineChart,
ColumnChart,
AreaChart,
BubbleChart,
CandlestickChart,
ComboChart,
GeoChart,
ScatterChart,
SteppedAreaChart,
TableChart
}
// Methods
public GoogleChart()
{
this.title = "Google Chart";
this.width = 730;
this.height = 300;
this.elementId = "chart_div";
}
public void addColumn(string type, string columnName)
{
string data = this.data;
this.data = data + "data.addColumn('" + type + "', '" + columnName + "');";
}
public void addRow(string value)
{
this.data = this.data + "data.addRow([" + value + "]);";
}
public string generateChart(ChartType chart)
{
this.javascript = "<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>";
this.javascript = this.javascript + "<script type=\"text/javascript\">";
this.javascript = this.javascript + "google.load('visualization', '1.0', { 'packages': ['corechart']});";
this.javascript = this.javascript + "google.setOnLoadCallback(drawChart);";
this.javascript = this.javascript + "function drawChart() {";
this.javascript = this.javascript + "var data = new google.visualization.DataTable();";
this.javascript = this.javascript + this.data;
this.javascript = this.javascript + "var options = {";
this.javascript = this.javascript + "'title': '" + this.title + "',";
object javascript = this.javascript;
this.javascript = string.Concat(new object[] { javascript, "'width': ", this.width, ", 'height': ", this.height, "};" });
string str = this.javascript;
this.javascript = str + "var chart = new google.visualization." + chart.ToString() + "(document.getElementById('" + this.elementId + "'));";
this.javascript = this.javascript + "chart.draw(data, options);";
this.javascript = this.javascript + "} </script>";
return this.javascript;
}
}
}
You can then use it by doing the following:
private void GenerateQuickStats()
{
GoogleChart chart = new GoogleChart();
chart.title = "Quick Stats";
chart.width = 250;
chart.height = 200;
chart.addColumn("string", "Year");
chart.addColumn("number", "Value");
chart.addColumn("number", "Profit");
chart.addRow("'2014', 2000, 1000");
// asp literal
ltChart.Text = chart.generateChart(GoogleChart.ChartType.ColumnChart);
}
Since David addressed the color issue, I'll tackle the animations. Animating the chart on first draw is a bit complicated; you have to draw it once with a zero'd out data set, and then draw it again with the real data set. Here's some javascript (that you can add to your string builder, replacing the chart creation and drawing lines) that will animate the chart:
var view = new google.visualization.DataView(data);
view.setColumns([0, {
sourceColumn: 1,
calc: function () {return 0;}
}, 2]);
var chart = new google.visualization.ColumnChart(document.getElementById('course_div'));
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
chart.draw(data, {
width: 650,
height: 300,
title: 'Course Enrollment',
color: '#0092CB',
hAxis: {
title: 'Course Title',
titleTextStyle: {
color: 'green'
}
},
animation: {
duration: 1000
}
});
});
chart.draw(view, {
width: 650,
height: 300,
title: 'Course Enrollment',
color: '#0092CB',
hAxis: {
title: 'Course Title',
titleTextStyle: {
color: 'green'
}
},
animation: {
duration: 1000
}
});
[Edit - attempt at C# example]
private void BindCourseChart()
{
//to bind course chart
DataTable dt = new DataTable();
try
{
dt = GetData_Course();
str.Append(#"
<script type=text/javascript>
google.load( *visualization*, *1*, {packages:[*corechart*], callback:drawChart});
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Title');
data.addColumn('number', 'Users enrolled');
**//Here I am adding role=style for customizing**
data.addColumn({type: 'string', role: 'style'});
data.addRows(" + dt.Rows.Count + ");
");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i] ["Title"].ToString() + "');");
str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["MenteeCount"].ToString() + ") ;");
}
str.Append(#"
var view = new google.visualization.DataView(data);
view.setColumns([0, {
sourceColumn: 1,
calc: function () {return 0;}
}, 2]);
var chart = new google.visualization.ColumnChart(document.getElementById('course_div'));
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
chart.draw(data, {
width: 650,
height: 300,
title: 'Course Enrollment',
color: '#0092CB',
hAxis: {
title: 'Course Title',
titleTextStyle: {
color: 'green'
}
},
animation: {
duration: 1000
}
});
});
chart.draw(view, {
width: 650,
height: 300,
title: 'Course Enrollment',
color: '#0092CB',
hAxis: {
title: 'Course Title',
titleTextStyle: {
color: 'green'
}
},
animation: {
duration: 1000
}
});
}
</script>
");
lt_course.Text = str.ToString().TrimEnd(',').Replace('*', '"');
}
I believe you are missing quotation marks around your color...
At the end of this line:
str.Append(" chart.draw(data, {width: 650, height: 300, title: 'Course Enrollment', color:#0092CB,");
you need apostrophes around the hex color:
str.Append(" chart.draw(data, {width: 650, height: 300, title: 'Course Enrollment', color:'#0092CB',");
If that doesn't work, compare the javascript that your app generates with your manually created code.

Categories

Resources