I have a .Net Core application and in one of my views I want to have a Google Map in which I want to be able to draw dynamical polylines.
Index.cshtml
I have included a Google Map on my view as follows:
<div class="col-md-6 col-lg-6">
<h3>My Google Maps Demo</h3>
<div id="map"></div>
</div>
<script>
function initMap() {
var center = { lat: 55.92965249, lng: 12.47840507 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: uluru
});
$.get()
$.post()
route.setMap(map);
}
</script>
And in my _Layout.cshtml I have:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=...api key...&callback=initMap">
</script>
All of this works as intended, but I am unsure of whether this is the proper way to show Google Maps in a .Net Core application?
Furthermore I want to be able to draw dynamical routes in my Google Maps implementation. This is done via the following code
var route = new google.maps.Polyline({
path: routeCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
where routeCoordinates is a list of coordinates:
var routeCoordinates = [
{lat: 55.92965249, lng: 12.47840507},
{lat: 55.92941392, lng: 12.47832253},
{lat: 55.92918626, lng: 12.47824027},
...
{lat: 55.91474539, lng: 12.47145191},
{lat: 55.91450191, lng: 12.47139283},
{lat: 55.91425197, lng: 12.47134614}
]
All the above is of course done statically in my Index.cshtml.
So is there a better way to do this? And how would I go about adding and removing lines dynamically (hopefully) by using my Controller? I expect something like:
public async Task<IActionResult> Index()
{
return View(await _context.Trips.ToListAsync());
//context is my db
}
Right now it is not present but I will be getting a list of coordinates from my context through my EF implementation.
EDIT:
Since I posted this I have continued a bit, and I now have a PartialView that I want to load when clicking a table row:
MapPartialView.cshtml
#model IEnumerable<LngLat>
<div class="col-md-6 col-lg-6">
<h3>My Google Maps Demo</h3>
<div id="map"></div>
</div>
<script>
function initMap() {
var center = { lat: 55.92965249, lng: 12.47840507 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: center
});
//$.get();
//$.post();
routeCoordinates = #Model;
var route = new google.maps.Polyline({
path: routeCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
route.setMap(map);
}
</script>
And my:
Index.cshtml
// table header and so forth..
<tbody>
#foreach (var item in Model)
{
<tr class="trips" data-id="#item.TripID" data-url="#Url.Action("ExpandMap", "Trip")">
<td>
#Html.DisplayFor(modelItem => item.DeviceID)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartTime)
</td>
<td>
#Html.DisplayFor(modelItem => item.Duration)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartLocation)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndLocation)
</td>
</tr>
}
</tbody>
<div id="partialMap"></div>
And in my:
site.js
$('.trips').each(function (i, e) {
var _this = $(this);
var element = $(e).children('td');
element.click(function () {
//console.log("Clicked! " + _this.data('url') + " " + _this.data('id'));
$("#partialMap").load(_this.data('url'), { id: _this.data('id') }, function () {
$("#partialMap").slideDown('200');
});
});
});
And lastly my controller and the ExpandMap function:
TripController.cs
public IActionResult ExpandMap(int id)
{
var trip = _context.Trips.SingleOrDefault(t => t.TripID == id);
List<LngLat> routeCoordinates = new List<LngLat>
{
new LngLat() { lat = 55.92965249, lng = 12.47840507},
new LngLat() { lat = 55.92941392, lng = 12.47832253},
...
new LngLat() { lat = 55.91450191, lng = 12.47139283},
new LngLat() { lat = 55.91425197, lng = 12.47134614}
};
string routeCoordinatesJS = JsonConvert.SerializeObject(routeCoordinates, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
return PartialView("MapPartialView", routeCoordinatesJS);
}
But when I run the code I get a:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
You can export your context to a list of lat and lng
public class LngLat
{
public double lat { get; set; }
public double lng { get; set; }
}
The build your list with data from your db and send it to the View():
public async Task<IActionResult> Index()
{
List<LngLat> routeCoordinates = await _context.Trips.Select(c=> new LngLat {lat = c.latitude, lng = c.longitude })
//Serialize your routeCoordiamte with Json.Net
string routeCoordinatesJs = JsonConvert.SerializeObject(routeCoordinates, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })
return View(routeCoordinatesJs);
}
In your View():
var routeCoordinates = #Model
Related
I implemente dynamic add and remove column it's working fine if I remove last row but if I remove first index then it's losing all other rows.
But if I use FormCollection Its binding but not as array list
public ActionResult Index()
{
var employee = new Employee();
employee.Skills.Insert(0, new Skill());
return View(employee);
}
.cshtml
<table id="skills-table">
<thead>
<tr>
<th style="width:20px;"> </th>
<th style="width:160px;">Skill</th>
<th style="width:150px;">Level</th>
<th style="width:32px;"> </th>
</tr>
</thead>
<tbody>
#for (var j = 0; j < Model.Skills.Count; j++)
{
<tr valign="top">
<th><span class="rownumber"></span></th>
<td>
#Html.TextBoxFor(model => model.Skills[j].Title, new { #class = "skill-title" })
#Html.ValidationMessageFor(model => model.Skills[j].Title)
</td>
<td>
#Html.DropDownListFor(
model => model.Skills[j].Level,
new SelectList(WebApplication4.MetaModels.SkillLevel.GetSkillLevels(), "Code", "Description", Model.Skills[j].Level),
"-- Select --",
new {#class = "skill-level"}
)
#Html.ValidationMessageFor(model => model.Skills[j].Level)
</td>
<td>
#if (j < Model.Skills.Count - 1)
{
<button type="button" class="remove-row" title="Delete row"> </button>
}
else
{
<button type="button" class="new-row" title="New row"> </button>
}
</td>
</tr>
}
</tbody>
</table>
jQuery:
<script type="text/javascript">
var addRow = function () {
addTableRow($("#skills-table"));
return false;
};
var deleteRow = function (event) {
$(event.target).closest("tr").remove();
return false;
};
function addTableRow(table) {
/* Sources:
http://www.simonbingham.me.uk/index.cfm/main/post/uuid/adding-a-row-to-a-table-containing-form-fields-using-jquery-18
http://stackoverflow.com/questions/5104288/adding-validation-with-mvc-3-jquery-validator-in-execution-time
*/
var $ttc = $(table).find("tbody tr:last");
var $tr = $ttc.clone();
$tr.find("input,select").attr("name", function () { // find name in the cloned row
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts from id, including index
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new name
}).attr("id", function () { // change id also
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts
return parts[1] + "_" + ++parts[2] + "__" + parts[3]; // build new id
});
$tr.find("span[data-valmsg-for]").attr("data-valmsg-for", function () { // find validation message
var parts = $(this).attr("data-valmsg-for").match(/(\D+)\[(\d+)]\.(\D+)$/); // extract parts from the referring attribute
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new value
})
$ttc.find(".new-row").attr("class", "remove-row").attr("title", "Delete row").unbind("click").click(deleteRow); // change buttin function
$tr.find(".new-row").click(addRow); // add function to the cloned button
// reset fields in the new row
$tr.find("select").val("");
$tr.find("input[type=text]").val("");
// add cloned row as last row
$(table).find("tbody tr:last").after($tr);
// Find the affected form
var $form = $tr.closest("FORM");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// We could re-validate with changes
// $form.validate($form.data("unobtrusiveValidation").options);
};
(function ($) {
/* Source:
http://www.johnculviner.com/post/2011/11/16/ClearReset-MVC-3-Form-and-Unobtrusive-jQuery-Client-Validation.aspx
*/
$.fn.resetValidation = function () {
var $form = this.closest('form');
//reset jQuery Validate's internals
$form.validate().resetForm();
//reset unobtrusive validation summary, if it exists
$form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul").empty();
//reset unobtrusive field level, if it exists
$form.find("[data-valmsg-replace]")
.removeClass("field-validation-error")
.addClass("field-validation-valid")
.empty();
return $form;
};
})(jQuery);
$(function () {
$(".new-row").click(addRow);
$(".remove-row").click(deleteRow);
})
</script>
Controller:
public ActionResult Index(Employee employee, FormCollection abc, string[]dynamic)
{
return View(employee);
}
Here my FormCollection is getting all the data but not as array type
As a newbie in ASP.NET Core, this is my first time trying to make an ajax call to asp.net controller method with jquery and I am finding it difficult. Below is my view form, my javascript file and my controller method;
The view form
<form id="components-form">
#Html.AntiForgeryToken();
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="entryformLabel">Payment Entries</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped" id="list-table">
<thead>
<tr>
<th>Entry</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
#foreach (var ent in ViewBag.staffEntries)
{
<tr>
<th>#ent.EntryLabel</th>
<th><input type="text" class="form-control entry" name="component[#ent.EntryId]" id="#ent.EntryId" value="#ent.EntryValue" /></th>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="update-entries-btn" class="btn btn-success"><span class="fa fa-check"></span> Update Entries</button>
</div>
</form>
The Javascript file
$(document).ready(function ()
{
var updateBtn = $("#update-entries-btn").click(function ()
{
$("#update-entries-btn").click(function () {
var token = $("[name=__RequestVerificationToken").val();
var postedValues = new FormData();
postedValues.append("__RequestVerificationToken", token);
$(".entry").each(function () {
var id = this.id;
var val = this.val;
postedValues.append(id,val);
});
var postUrl = "/staff/updatecomponents";
$.post(postUrl, postedValues, function (result) {
alert(result);
});
})
})
}
);
The controller method. I'm actually lost on how to handle the request at this point. Doint this returns null.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult updatecomponents(string posted)
{
return Json(posted);
}
I will appreciate a guide to get this working.
Thank you
After some more research, I solved this thus:
The Javascript code
$(document).ready(function ()
{
$("#update-components-btn").click(function ()
{
var token = $("[name=__RequestVerificationToken").val();
var staffId = $("[name=staffId").val();
var postedValues = {};
postedValues["__RequestVerificationToken"] = token;
postedValues.StaffId = staffId;
postedValues.StaffComponents = [];
$(".entry").each(function ()
{
var component = {};
component.StaffId = staffId;
component.EntryId = $(this).attr('id');
component.ValueAmount = Number($(this).val());
postedValues.StaffComponents.push(component);
});
var postUrl = "/staff/updatecomponents";
$.post(postUrl, postedValues, function (result)
{
var report = JSON.parse(JSON.stringify(result));
if (report.status)
{
swal("<span class=fa fa-thumbs-up", report.message, "success");
setInterval(function () { window.location.reload(true); }, 5000);
}
else
{
swal("<span class=fa fa-thumbs-down", report.message, "error");
}
});
});
}
);
I had to create a model that would emulate the expected object
public class StaffEntryUpdateModel
{
public string RequestToken { get; set; }
public string StaffId { get; set; }
public List<StaffEntry> StaffComponents { get; set; }
}
And finally the server side endpoint that receives and processes the ajax post
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult updatecomponents(StaffEntryUpdateModel postedData)
{
try
{
if (postedData.StaffComponents.Any())
{
ApplicationUser Staff = db.Users.FirstOrDefault(s => s.Id == postedData.StaffId);
if (Staff == null)
{
return new JsonResult(new { Status = false, Message = "Unknown staff" });
}
db.StaffEntries.Where(se => se.StaffId == postedData.StaffId).Delete();
foreach (var c in postedData.StaffComponents)
{
db.StaffEntries.Add(c);
}
int inserted = db.SaveChanges();
return new JsonResult(new { Status = (inserted > 0) ? true : false, Message = inserted + " components updated for staff" });
}
else
{
return new JsonResult(new { Status = false, Message = "No component sent for update for staff" });
}
}
catch (Exception e)
{
return new JsonResult(new {Status=false,Message=e.Message.ToString() });
}
}
In the process of working and reviewing the code, I had to change some items from the way it appeared in the original question but its basically the same.
I hope this helps someone looking for such solution anytime.
Thank you #Chetan Ranpariya for your attempt to help
I am newbie in asp.net mvc.
I have 2 cascading dropdownlist and 1 file input on my page.
I made cascading dropdownlists following this tutorial. But when I trying to pass value to controller, there is an error System.ArgumentException, null parameter. I looked up the list of parameters using Firebug, but I can't find value of second dropdown at all.
My controller code is below:
public ActionResult Index()
{
List<SelectListItem> branchNames = new List<SelectListItem>();
FormatModel fmtModel = new FormatModel();
List<branch> branches = db.branch.ToList();
branches.ForEach(x =>
{
branchNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
fmtModel.BranchNames = branchNames;
return View(fmtModel);
}
[HttpPost]
public ActionResult GetPaymentSystem(string branchId)
{
int intBranchId;
List<SelectListItem> paymentSystemNames = new List<SelectListItem>();
if (!string.IsNullOrEmpty(branchId))
{
intBranchId = Convert.ToInt32(branchId);
List<paymentSysDTO> paymentSystems =
(from ps in db.paymentSys
join ps_br in db.br_ps_format on ps.id equals ps_br.ps_id
join br in db.branch on ps_br.branch_id equals br.id
where br.id == intBranchId
select new paymentSysDTO
{
id = ps.id,
name = ps.name,
code = ps.code
}
).ToList();
paymentSystems.ForEach(x =>
{
paymentSystemNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
}
return Json(paymentSystemNames, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Index(int BranchNames, int PaymentSystemNames, HttpPostedFileBase file)
{
//controller code
}
View code:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<legend>Введите данные:</legend>
<table>
<tr>
<td>
<label>Филиал</label>
</td>
<td>
#Html.DropDownListFor(x => x.BranchNames, Model.BranchNames, "Выбрать", new { id = "ddlBranch" })
</td>
</tr>
<tr>
<td>
<label>Платежная система/Банк</label>
</td>
<td id="PaymentSystem">
#Html.DropDownListFor(x => x.PaymentSystemNames, new List<SelectListItem>(), "Выбрать", new { #id = "ddlPaymentSystem" })
</td>
</tr>
<tr>
<td>
<input id="InputFile" type="file" name="file" />
</td>
</tr>
<tr>
<td>
<input id="ConvertButton" type="submit" value="Конвертировать" />
</td>
</tr>
</table>
}
#if (null != TempData["msg"])
{
#Html.Raw(TempData["msg"])
}
<script type="text/javascript">
$(function () {
$('#ddlBranch').change(function () {
$.ajax({
type: 'POST',
url: "/Home/GetPaymentSystem",
data: { branchID: $('#ddlBranch').val() },
datatype: "json",
traditional: true,
success: function (data) {
var paymentSystem = "<select id='ddlPaymentSystem'>";
paymentSystem = paymentSystem + '<option value ="">Select</option>';
for (var i = 0; i < data.length; i++)
{
paymentSystem = paymentSystem + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
paymentSystem = paymentSystem + '</select>';
$('#PaymentSystem').html(paymentSystem);
}
cas
});
});
});
</script>
Sorry for my English and thanks for ur help.
[HttpPost]
public ActionResult Charter(List<int> stateIds)
{
try
{
if (!stateIds.Any())
{
return Json("State list is empty", JsonRequestBehavior.AllowGet);
}
var states = new List<CfVersionEntities.Model.State>();
stateIds.ForEach(id =>
{
using (var db = new Storage_cfEntities())
{
var stateList = db.States.Where(i => i.Id == id).ToList();//get names of states with matching id and save in array named
if (!stateList.Any()) return;
var state = stateList[0];
states.Add(state);
}
});
return !states.Any() ? Json(new List<State>(), JsonRequestBehavior.AllowGet) : Json(states, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(new List<State>(),
JsonRequestBehavior.AllowGet);
}
}
I have a method that accepts values from my jquery scripts which is below, the script works fine and sends the values, the values are received in my method, i have confirmed that. but when i run it i get the error :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.... I am using the values from my jquery to loop through my database and select rows that have corresponding IDs, i am then sending this result back to another function in my jquery which creates a highchart with the values
This is my View which includes my script.
List Of States
<p>
<h2> #Html.ActionLink("Add A New State", "CreateState")</h2>
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Stations)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stations)
</td>
<td>
#Html.ActionLink("Update Stations", "UpdateStation", new {id = item.Id})||
<div>
<input type="checkbox" id="#item.Id" value="#item.Id" class="chk" onclick="setChecked(this)"> <label >Add to Chart</label>
</div>
</td>
</tr>
}
</table>
<div id="charts" style="width:100%" height="400px;"></div>
<input type="button" value="Verify Selections" onclick="submit()"/>
<input type="button" value ="View Chart" onclick="location.href='#Url.Action("Charter")'" />
<script type="text/javascript">
var collection = [];
function setChecked(el) {
var id = $(el).attr('id');
if ($(el).is(':checked'))
{
collection.push(id);
} else {
$.each(collection, function (item, index)
{
if (item === id)
{
collection.splice(index, 1);
}
});
}
}
function submit() {
if (collection == null || collection.length < 1) {
alert('please select at least one state.');
return;
}
$.ajax({
type: "POST",
url: '/State/Charter',
data: { stateIds: collection },
dataType: 'application/json',
success: function (response)
{
if (response.length > 0) {
designChart(response);
}
}
});
}
function designChart(response)
{
var names = [];
var stations = [];
$.each(response, function (item) {
if (item.Id > 0) {
names.push(item.Name);
stations.push(item.Stations);
}
});
$("#charts").highcharts({
chart:
{
type: 'line'
},
title: {
text: 'States'
},
xAxis: {
categories: names
},
yAxis:
{
title:
{
text: 'Stations',
categories: stations
}
}
});
}
</script>
I'm kinda new at JQuery and are stuck atm. I have an MVC application that draws charts from Google API. I'm working on a UI that alows the user to select a item from a DropDownList, click Run and the charts will load. My current problem is the charts are run directly when i go to the view. The JQuery function that draws the charts implements the GetData ActionResult in GAStatisticsController.
I have a dropDownList with selectable items from a model class and a button ("GAStatisticsReport-Submit"). I just need t check if item "Visitors" is selected in the DropDownList, if that's the case i can click run and the Charts will display the data with visitors. How could i archive this?
The controller has a method called CreateGAStatisticsReport wich returns data to the view for the charts to display. This method has an ActionResult. However when the function draws the charts it draws them from GetData ActionResult and not GAStatistics.
Here is the view:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.get('/GAStatistics/GetData', {}, <--- here's GetData ActionResult in the Controller
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('date', 'Datum');
tdata.addColumn('number', 'Besökare');
for (var i = 0; i < data.length; i++) {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
var options = {
title: "Number of unique visitors"
};
var chart1 = new google.visualization.AreaChart(document.getElementById('chart_div1'));
var chart2 = new google.visualization.LineChart(document.getElementById('chart_div2'));
var chart4 = new google.visualization.ColumnChart(document.getElementById('chart_div4'));
chart1.draw(tdata, options);
chart2.draw(tdata, options);
chart4.draw(tdata, options);
});
}
</script>
<table class="adminContent">
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.StartDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.StartDate)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.EndDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.EndDate)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.GAStatisticsId ):
</td>
<td class="adminData">
#Html.DropDownList("GAStatisticsId", Model.AvailableGAStatistics)
<input type="button" id="GAStatisticsReport-Submit" class="t-button" value="#T("Run")" />
</tr>
</table>
My ViewModel (note: When SelectListItem "Visitors is selected and the user has clicked the "Run" button it should execute and draw the charts):
public class GAStatisticsListModel : BaseNopModel
{
public GAStatisticsListModel()
{
AvailableGAStatistics = new List<SelectListItem>();
SelectListItem Visitors = new SelectListItem() { Text = "Besökare", Value = "1", Selected = false };
SelectListItem PercentNewVisitors = new SelectListItem() { Text = "Nya Besökare (Procent)", Value = "2", Selected = false };
SelectListItem ConversionRate = new SelectListItem() { Text = "Konverteringsgrad", Value = "3", Selected = false };
AvailableGAStatistics.Add(Visitors);
AvailableGAStatistics.Add(PercentNewVisitors);
AvailableGAStatistics.Add(ConversionRate);
}
[NopResourceDisplayName("Admin.ShopStatistics.List.StartDate")]
[UIHint("DateNullable")]
public DateTime? StartDate { get; set; }
[NopResourceDisplayName("Admin.ShopStatistics.List.EndDate")]
[UIHint("DateNullable")]
public DateTime? EndDate { get; set; }
[NopResourceDisplayName("Admin.GAStatistics.GAStatistics.GAStatisticsList")]
public int GAStatisticsId { get; set; }
public List<SelectListItem> AvailableGAStatistics { get; set; }
}
}
The Controller (GetData passes data to the JQuery code in the view from CreateGAStatisticsReport for the charts to display):
public class GAStatisticsController : Controller
{
//GET: /ShopStatistics/
[HttpPost]
public ActionResult GetData()
{
return Json(CreateGAStatisticsReport(), JsonRequestBehavior.AllowGet);
}
public ActionResult GAStatistics()
{
return View(new GAStatisticsListModel());
}
private List<GAStatistics> CreateGAStatisticsReport()
{
var serviceAccountEmail = "xxxxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"C:\Users\Desktop\NopCommerce\Presentation\Nop.Web\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
// Create the service.
//Twistandtango
var GoogleAnalyticsService = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyApp",
});
var request = GoogleAnalyticsService.Data.Ga.Get("ga:xxxxxxxx", "2014-01-24", "2014-01-30", "ga:visitors");
//Specify some addition query parameters
request.Dimensions = "ga:date";
request.Sort = "-ga:date";
request.MaxResults = 10000;
//Execute and fetch the results of our query
Google.Apis.Analytics.v3.Data.GaData d = request.Execute();
List<GAStatistics> ListGaVisitors = new List<GAStatistics>();
foreach (var row in d.Rows)
{
GAStatistics GaVisits = new GAStatistics(row[0], row[1]);
ListGaVisitors.Add(GaVisits);
}
return ListGaVisitors;
}
}
For what you want you can't use google.setOnLoadCallback(drawChart) (see this link too understand why). If I understand what you want to do, you must set a event on your button and that event will execute the drawChart() function.
Like this:
$("#GAStatisticsReport-Submit").click(function(){ drawChart() })
So, when you click on that button the chart will be draw.
To draw the chart only if the 'Visitors' is selected you must do something like this:
$("#GAStatisticsReport-Submit").click(function(){
if($("select[name='GAStatisticsId'] option:selected").text()=="Visitors")
drawChart()
})