MVC 4 PartialView - asp.net-mvc

I have MVC 4 Application and im using google maps to render my locations by retrieving latitude and longitude from the database.(My database is updated automatically by wcf data service through mobile device.)
In MVC Application i want to refresh the google map automatically in timely manner.
Following is my index page(Index.cshtml).
#model IEnumerable<MvcApplication17.Models.Train>
<div id="MapLocators">
#Html.Partial("Map_Locator", Model)
</div>
<script type="text/javascript">
$(function () {
setInterval(function () { $('#MapLocators').load('/Home/GetMap'); }, 3000);
});
</script>
Here is my Partial View under Home(Map_Locator.cshtml),
#model IEnumerable<MvcApplication17.Models.Train>
<div id="content-container">
<div id="map_canvas">
</div>
</div>
<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function(){
var bounds = new google.maps.LatLngBounds();
var mapoptions = { zoom:6}; //map options
var map = new google.maps.Map(document.getElementById('map_canvas'), mapoptions);
map.markers = [];
#foreach(var item in Model)
{
<text>
var poiLatLang = new google.maps.LatLng( #item.Latitude, #item.Longitrude);
var image = 'images/Train station.png';
var marker = new google.maps.Marker({
position: poiLatLang ,
map: map,
icon: image
});
bounds.extend(marker.position);
map.markers.push(marker);
</text>
}
map.fitBounds(bounds);
});
</script>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
Here is my Home Controller,
private TestContext db = new TestContext();
[OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)]
public ActionResult GetMap()
{
return PartialView("Map_Locator",db.Trains.ToList());
}
The problem is index page show the google maps only in first application loading stage and it doesn't refresh automatically.
Thanks

I solved the problem by calling map load function in following way,
<script>
$(function () {
setInterval(function () { $('#MapLocators').load('/Home/GetMap',function{}); }, 20000);
});
</script>

Related

Why my razor page not show google map?

I'm beginner in asp.net mvc ,i read down tutorial for write simple map web application:
this tutorial
So in my view page write this code:
#section Scripts {
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
}
<h2>Hello, Google Maps</h2>
<div id="map_canvas" style="width:400px; height:300px"></div>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = { zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById
("map_canvas"), options);
}
$(function () {
initialize();
});
</script>
but when i run the my project i cant see anything or map,what happen?how can i solve that problem?thanks.
i open firefox browser console and get this message:
The connection to ws://localhost:48472/fbc4eb4ba8f245c08d4b7830ea1bab80/browserLinkSignalR/connect?transport=webSockets&connectionToken=AQAAANCMnd8BFdERjHoAwE%2FCl%2BsBAAAAVMxSNM8YWkSjTNqVKDW%2FRgAAAAACAAAAAAAQZgAAAAEAACAAAABdm%2BiuJnxhF10BzDr1Z%2B7J6KR%2F%2BuJCWYOVuUONt67r8gAAAAAOgAAAAAIAACAAAACcPWAkFxp3Ue2b%2Fu4pg3M7Y3PvHkDLNZfT2ohQfLpWcDAAAAAeHVeKECzTOS87AKunnn2HMxQVjyac86hh6M%2FTjYF4YXxInAmM5wmBizj7UnQW32JAAAAAPgk7BG3rmPAhFQeTmLPjNLjB2Ow%2FbyNdPE5HyR4%2BRmJG3IdLX2om1zux8pxGME9jhfhw3C3AP0e1r5y1JrLtAw%3D%3D&requestUrl=http%3A%2F%2Flocalhost%3A31095%2FGoogleMap%2FGoogleMap&browserName=Firefox&userAgent=Mozilla%2F5.0+(Windows+NT+10.0%3B+WOW64%3B+rv%3A43.0)+Gecko%2F20100101+Firefox%2F43.0&tid=6 was interrupted while the page was loading. browserLink:62:20265
ReferenceError: $ is not defined
GoogleMap:33:5
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.
You don't need jquery for run initialize you simply can add
google.maps.event.addDomListener(window, 'load', initialize);
.
this way
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = { zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById
("map_canvas"), options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
try using
#section Scripts {
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?"></script>
}
You need to use either Jquery
or simply call the method at bottom so the whole code should be like
function initialize() {
var latlng = new google.maps.LatLng(40.716948, -74.003563);
var options = { zoom: 14, center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
}
initialize();
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<h2>Hello</h2>
<div id="map_canvas" style="width:400px; height:300px"></div>
initialize();
and it should work.

Google Fusion Map Info Window Not Formatted

I have created a Google Fusion Map with 2 layers. All appears to be working correctly with 1 exception.
I have formatted the Info Window of both layers using the Google Fusion Table tool. However, the Info Window on layer 1 is not appearing as specified with the code below. It works fine in the Google Fusion Table tool itself.
Can anyone spot what I've done wrong? Thanks.
<meta charset="UTF-8">
<title>Smithfield Foods UK</title>
<link rel="stylesheet" type="text/css" media="all" href="FusionMapTemplate.css" />
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var defaultZoom = 10;
var defaultCenter = new google.maps.LatLng(52.6500, 1.2800)
var locationColumn = 'geometry'
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: defaultCenter,
zoom: defaultZoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
// Initialize the first layer
var FirstLayer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1hpGzmMBg8bDgPOGrAXvc0_QVLSBqQ0O5vpLbfUE'
},
map: map,
styleId: 3,
templateID: 5,
suppressInfoWindows: true
});
google.maps.event.addListener(FirstLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
// Initialize the second layer
var SecondLayer = new google.maps.FusionTablesLayer({
query: {
select: 'PostCode',
from: '1RrCcRC-1vU0bfHQJTQWqToR-vllSsz9iKnI5WEk'
},
map: map,
styleId: 2,
templateId: 2,
suppressInfoWindows: true
});
google.maps.event.addListener(SecondLayer, 'click', function(e) {windowControl(e, infoWindow, map);
});
}
// Open the info window at the clicked location
function windowControl(e, infoWindow, map) {
infoWindow.setOptions({
content: e.infoWindowHtml,
position: e.latLng,
pixelOffset: e.pixelOffset
});
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
the issue:
templateID: 5,
//-------^
the D has to be lowercase

asp.net mvc + knockout + ajax partial load + reuse viewodel and load different data within the same page

In a single asp.net MVC page, I've to show 3 reports of same layout/structor. So I created a page that generated a report using Knockout databind and 10 reports are generated by passing some additional parameters.
I tried to load all 3 reports using Ajax partial view and by this way I'm populating those 10 reports in one single page.
Now I happen to see a strange issue, the last report data appears for all the 3 reports though the data for each report is different. Anyone knows how to handle this issue ?
Main Page View, where I call 3 reports via Ajax call.
<div id="RecentlyAddedReport" ></div>
<div id="RecentlyConsultedReport"></div>
<div id="RecentlyPrescribedReport"></div>
<!-- start here -->
<script type="text/javascript">
$(document).ready(function () {
AjaxLoadReport('RecentlyAddedReport', 'Patient/Report?type=RecentlyAdded&name=Recently Added');
AjaxLoadReport('RecentlyConsultedReport', 'Patient/Report?type=RecentlyConsulted&name=Recently Consulted');
AjaxLoadReport('RecentlyPrescribedReport', 'Patient/Report?type=RecentlyPrescribed&name=Recently Prescribed');
});
function AjaxLoadReport(reportType, actionURL) {
var resultDiv = $('#' + reportType);
$.ajax({ type: "GET", url: actionURL, data: {},
success: function (response) {
resultDiv.html('');
resultDiv.html(response);
}
});
}
</script>
Report View - I call this same view for all the 3 reports
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<TryHomeo.Web.UI.Models.UserControlViewData>" %>
<script type="text/javascript" src="../../scripts/jquery-1.7.1.min.js"></script>
<script src="../../Scripts/jquery.timeago.js" type="text/javascript"> </script>
<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"> </script>
<h1>
<%:Model.ReportName%>
</h1>
<div class='loadingIndicator' title="Loading..."></div>
<ul id="<%=Model.ReportType %>" data-bind="template: { name: 'patient-template', foreach: patients}"></ul>
<script type="text/html" id="patient-template">
<span>
<li>
<div>
<a data-bind="text: PatientName"></a>- (<abbr class='timeago' data-bind="timeago: DatedString"></abbr>)
</div>
</li>
</span>
</script>
<script type="text/javascript">
// ReportViewModel View Model //
function ReportViewModel() {
var self = this;
self.patients = ko.observableArray([]);
}
var objVM = new ReportViewModel();
ko.applyBindings(objVM);
// Using jQuery for Ajax loading indicator
$(".loadingIndicator").ajaxStart(function () { $(this).fadeIn(); }).ajaxComplete(function () { $(this).fadeOut(); });
$(document).ready(function () {
$.ajax({
dataType: 'json',
url: '/Patient/GetPatientReport/?type=' + '<%=Model.ReportType %>' + '&' + '<%=DateTime.Now.ToString() %>',
success: SetData,
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
});
function SetData(data) {
objVM.patients(data);
}
ko.bindingHandlers.timeago = {
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var $this = $(element);
// Set the title attribute to the new value = timestamp
$this.attr('title', value);
// If timeago has already been applied to this node, don't reapply it -
// since timeago isn't really flexible (it doesn't provide a public
// remove() or refresh() method) we need to do everything by ourselves.
if ($this.data('timeago')) {
var datetime = $.timeago.datetime($this);
var distance = (new Date().getTime() - datetime.getTime());
var inWords = $.timeago.inWords(distance);
// Update cache and displayed text..
$this.data('timeago', { 'datetime': datetime });
$this.text(inWords);
} else {
// timeago hasn't been applied to this node -> we do that now!
$this.timeago();
}
}
};
</script>

Displaying markers on Google Map with the help of several longitude' and latitude's

I want to display several placemarkers on the map with the help of lat's and long's that I have in my controller. There are no build errors and I am also able to see the map with the various placemarker but only the last info window is responding to the click event.
#section Script {
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
}
<div id="map_canvas" style="width: 875px; height: 600px">
</div> `
<script type="text/javascript">
//display the map
var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var myOptions = {
zoom: 4,
center: stockholm,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//display markers
#foreach (var item in Model)
{
<text>
var latLng = new google.maps.LatLng('#(item.Latitude)', '#(item.Longitude)');
var title = '#(item.Title)';
var contentString = '<h3>' + title + '</h3>'
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(contentString);
infoWindow.open(map, marker);
});
</text>
}
</script>
For each item in the model you are creating a marker. However the code to add the event listener to the marker (for the click ) is outside of the loop.
The event listener is only being added to the last marker, not every marker.

ASP.NET MVC | Problem about showing modal dialog using jQuery dialog widget

I am very fresh to asp.net mvc and jQuery. After one day trying, I still don't know how to pop up a jQuery dialog using data from a action(return JsonResult) while user click a link.
Any suggest or guideline is appreciate.
Thanks!
Thx for Stuntz & RhinoDevX64 's reply, finally I work it out.
jQuery Code:
<script type="text/javascript">
$(function() {
$('.newsitem').click(function() {
var $thisLink = $(this);
$('#dialog').empty();
$.getJSON($thisLink.attr("href"), function(data) {
$('#dialog').html(data.content);
$("#dialog").dialog({
autoOpen: false,
title: data.title,
bgiframe: true,
modal: true,
height: 450,
width: 540,
buttons: {
'关闭': function() {
$(this).dialog('close');
}
}
});
$('#dialog').dialog('open');
});
return false;
});
});
</script>
ActionLink
<%= Html.ActionLink(item.Title, "GetByJs", "Article", new { id = item.ID }, new { #class = "newsitem" })%>
Action Code
public ActionResult GetByJs(Guid id) {
var item = Article.SingleOrDefault(a => a.ID == id && a.AtFront == true);
var jsonData = new {
title = item.Title, content = item.BodyContent
};
return new JsonResult {
Data = jsonData
};
}
var ph = $("#idOfPlaceHolderInPage");
ph.load(/Controller/SomeActionWhichReturnsPartialView, function() {
// this callback will be called after your partial view loaded into placeholder
ph.dialog({
// pass options here to customize dialog
});
});
1st use jQuery UI follow their documentation for including the css and js files.
<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
<script src="../../Scripts/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script>
<link href="../../Content/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function(){
$("#idOfModalPlaceholder").dialog({autoOpen: false, title:"MODAL TITLE"});
});
function OpenModalGetContent(){
$("#idOfModalPlaceHolder").load("/Controller/View");
$("#idOfModalPlaceHolder").dialog('open');
}
</script>
CLICK HERE FOR MODAL
2nd You should really just use a regular ActionResult and a Partial View (*.ascx), if you are just grabbing some content;
if you are calling data I presume you may be loading into an autocomplete which would be completely different than this scenario.

Resources