google maps + asp .net mvc 3 not working - asp.net-mvc-3

I am teaching myself asp .net mvc 3. I read this tutorial: http://www.codeproject.com/Articles/148949/ASP-NET-MVC-3-the-Razor-View-Engine-and-Google-Map and several other such posts. However, I have not been able to get google map running on my application. what am I doing wrong?
View:
#section Scripts_head {
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
}
<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"), options);
}
$(function () {
initialize();
});
</script>
<div id="map" style="width:80%; height:80%"></div>
I have also tried putting the div over the script tag.
Layout Page:
<head>
...
#RenderSection("Scripts_head", false)
</head>
Controller:
public class MapController : Controller
{
//
// GET: /Map/
public ActionResult Index()
{
return View();
}
}

If you dont have errors, then its probably sizing of your div "map". Here is your code extracted and working in JsFiddle:
http://jsfiddle.net/GNwU8/3/

Give you map div an absolute size. You have:
<div id="map" style="width:80%; height:80%"></div>
...but that is 80% of what?
instead try:
<div id="map" style="width:400px; height:300px"></div>

Related

how to load a partial view ona selector using jquery?

var uri="#Url.Content("/Views/Shared/_LogOnPartial")";
$("#logindisplay").load(uri);
it give me error
Files with leading underscores ("_") cannot be served.
why the url don't work.
You can use following code to load Partial Views in ~/Views/Shared/ Folder.
<script type="text/javascript">
$(document).ready(function () {
$("#btnclick").click(function () {
var uri = '#Url.Content("_LogOnPartial")';
$("#logindisplay").load(uri);
});
});
</script>
HTML is,
<input type="button" id="btnclick" value="Load View" />
<div id="logindisplay">
</div>
You should use
"#Html.Partial("/Views/Shared/_LogOnPartial)
to load partial instead of #Url.Content("/Views/Shared/_LogOnPartial")
best practice is to define path for partials, Layouts & views earlier
in App_Start/RouteConfig write method like below
public static void RegisterViewEngines(ICollection engines)
{
/*
* {0} = view name
* {1} = controller name
*/
engines.Clear();
engines.Add(new RazorViewEngine
{
ViewLocationFormats = new[] { "~/Views/{0}.cshtml" },
MasterLocationFormats = new[] { "~/Views/Shared/{0}.cshtml" },
PartialViewLocationFormats = new[] { "~/Views/Partial/{0}.cshtml" }
});
}
then execute it in Globa.asax like
RouteConfig.RegisterViewEngines(ViewEngines.Engines);
then you can easily call partial like this
#Html.Partial("_LogOnPartial");

Trying to load a partial view with Ajax.ActionLink

After reading a few other posts on here I've got this far with attempting to load a partial view on the click of a link (the text link may actually change to be an image once I get past this proof of concept stage). The problem is I am being directed to the partial view on click instead of it populating a div within the view I am clicking the link on:
The layout:
<script src="#Url.Content("~/scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
The View:
#Ajax.ActionLink("Item 1 Ajax", "Details", "Portfolio", new { name = "test" }, new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "row1Content",
OnComplete = "portfolioItemLoaded"
})
<div id="row1content"></div>
<script type="text/javascript">
function portfolioItemLoaded() {
alert("Done");
}
</script>
The controller:
public class PortfolioController : Controller
{
public ActionResult Details(string name)
{
return PartialView(name);
}
}
The partial (obviously named test.cshtml):
<p>Item 1 test</p>
Have I missed something obvious? It's the first time I have attempted to use AJAX in MVC, so there might be a school boy error or two.
I am planning on having several different Ajax Action Links that call different partial views, hence the reason I am passing the name in to the controller.
Code fixed
Do you wanna try this, you have a better control, if error, etc....
HTML with helper
#Html.ActionLink("Item 1 Ajax", "Details", "Portfolio", Nothing, New With {.Id = "myLink"})
JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('#myLink').click(getIt);
});
function getIt() {
$.ajax({
type: "POST",
url: $(this).attr('href'),
error: function () {
//show error handler
},
success: function (r) {
$('#row1content').html(r);
}
});
return false;
}
</script>

How to use knockout.js in MVC 3 Razor?

i am newbie knockout.js. Also i ama upper intermadiate in asp.net mvc 3. i really want to learn how to use knockout js in mvc 3 razor? but below code is not working also return to me empty total price. There is no error. Help please thanks...
Model:
public class GiftModel
{
public string Title { get; set; }
public double Price { get; set; }
}
View:
#using System.Web.Script.Serialization;
#model IEnumerable<knockout1.Models.GiftModel>
#{
ViewBag.Title = "Index";
}
<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script type="text/javascript">
var initialData = #(new JavaScriptSerializer().Serialize(Model));
var viewModel = {
gifts : ko.observableArray(initialData)
};
ko.applyBindings(viewModel);
</script>
<h2>Index</h2>
<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
Controller:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
var initialState = new[] {
new GiftModel { Title = "Tall Hat", Price = 49.95 },
new GiftModel { Title = "Long Cloak", Price = 78.25 }
};
return View(initialState);
}
}
I guess you are following this tutorial.
You have a couple of errors. First replace:
var initialData = #(new JavaScriptSerializer().Serialize(Model));
with:
var initialData = #Html.Raw(Json.Encode(Model));
This ensures that your model is properly JSON encoded. In the original article Steven Sanderson is using the WebForms view engine but you seem to be using the Razor view engine. So make sure that you adapt your syntax accordingly (don't forget that the # razor function automatically html encodes the output contrary to the <%= WebForms syntax).
And the second problem with your code is that you attempted to bind your knockout model before your DOM is ready (i.e. you have placed the ko.applyBindings(viewModel); call before the actual span containing the bindings). So either wrap your call in a $(document).ready or place your scripts at the end of the document, just before closing your </body> tag (recommended).
Also I would recommend you using url helpers to reference your scripts, don't just hardcode those urls, your application will break as soon as you publish in IIS:
#model IEnumerable<GiftModel>
<h2>Index</h2>
<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
<script src="#Url.Content("~/Scripts/knockout-2.1.0.js")" type="text/javascript"></script>
<script type="text/javascript">
var initialData = #Html.Raw(Json.Encode(Model));
var viewModel = {
gifts : ko.observableArray(initialData)
};
ko.applyBindings(viewModel);
</script>
So as you can see the 2 problems you were having have strictly nothing to do with knockoutjs. So what I would recommend you if you want to learn some framework is to learn it independently. Don't mix up technologies or you will get mixed up.
So go ahead over the knockoutjs site and start the tutorials working on static HTML pages. Forget about ASP.NET MVC for the moment. Forget about Entity Framework. Just learn the framework starting from a static HTML page. This way you will better understand how it works.

MVC Partial view hides main view

I am new to MVC. using MVC 3.
I have PersonMaster Controller as below... having following two Actions.
public ActionResult TopTenPersons()
{
Thread.Sleep(2000);
var persons = DatabaseHelper.Instance.Database.Query<Person_Master>("select top(10) from person_master").ToList();
return View("_PersonGrid", persons);
}
public ActionResult Index()
{
var persons = DatabaseHelper.Instance.Database.Query<Person_Master>("select * from person_master").ToList();
return View("_PersonGrid",persons);
//return View();
}
Then, index.cshtml view is as follows..
#model System.Collections.Generic.ICollection<MyPracticeApp1.Models.Person_Master>
#section scripts{
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
<h2>Persons</h2>
<p>
#Ajax.ActionLink("Click to top 10 Persons","TopTenPersons", new AjaxOptions{
UpdateTargetId="tbl_person",
InsertionMode=InsertionMode.Replace,
HttpMethod="GET"
})
</p>
<div id="tbl_person">
#Html.Action("Index","PersonMaster");
</div>
..and partial view _PersonGrid.cshtml which is called above in index view is as follows...
#model System.Collections.Generic.ICollection<MyPracticeApp1.Models.Person_Master>
#{
var persongrid = new WebGrid(Model);
}
#persongrid.GetHtml()
....But problem is that it directly shows partial view. It is not rendering Ajax Actionlink of index view. So, where is the mistake?
Change TopTenPersons to return a Partial View, not a View
public ActionResult Index()
{
var persons = DatabaseHelper.Instance.Database.Query<Person_Master>("select * from person_master").ToList();
return PartialView("_PersonGrid",persons);
}
add layout=null to _PersonGrid.cshtml
seems like
#{
Layout = null;
}
when you add this code It is not rendering full view..

Ajaxified link in MVC3/JQuery not working in IE8 (missing header)

Consider the following code (it is based on a default EMPTY MVC3 project created in visual web developer express 2010sp1):
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div id="header">header</div>
<div id="main">#RenderBody()</div>
</body>
</html>
Index method of HomeController:
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
ViewBag.Message = "partial";
return PartialView();
}
else
{
ViewBag.Message = "full";
return View();
}
}
Index.cshtml:
<script type="text/javascript">
$(function () {
$('#myLink').click(function () {
$.post(this.href, function (result) {
$('#main').html(result);
alert(result);
});
return false;
//$('#main').load(this.href);
//return false;
});
});
</script>
HomeController index. #ViewBag.Message
#Html.ActionLink("Index", "Index", new { controller = "Home" }, new { id = "myLink" } );
The problem is that in IE8 when the myLink link is clicked, it doesn't update the main div with only the partial html from Index.cshtml but the complete html including the layout. Ofcourse it works fine in FF, I mean why shouldn't it right? It seems Request.IsAjaxRequest() always evaluates to false in IE8. I understand that it is a result of a header X-Requested-With not being attached to a request in IE8. I don't have a lot of experience with web development -- is this a common issue and what is the (best) way to solve this?
UPDATE:
Yesterday I got it working normally in IE8, but when I tried it again this morning, the same problem was back. Now I don't think it has anything to do with the settings in IE8 anymore as I restored the settings to the default values. I tried examining the request with the fiddler tool. In order for me to be able to capture the traffic from localhost with fiddler, I added a period to the address: http://localhost.:3157/. So now the error occurs only when I use http://localhost.:3157/ (with period) and it works normally when I use http://localhost:3157/ (without period). I additionally tested the behavior in Chrome, Opera and Safari -- the ajax link works normally in these browsers. Note that I can get it working normally in IE8 when I attach a query parameter to the ajax link like so:
#Html.ActionLink("Index", "Index", new { controller = "Home", param = "param" }, new { id = "myLink" } )
I don't really want to do this. I'm running low on ideas here. I'm probably missing something that is blatantly obvious to a seasoned web developer =] Anybody recognize these symptoms?
You probably want to use the .live() method instead of .click():
$('#myLink').live('click', function () {
...
return false;
});
because you are replacing the DOM in the AJAX callback (the #main) which contains the link so you are killing the event handler you have assigned.
Also you have a typo in the jquery script inclusion in the <head>. You are missing a closing > after type="text/javascript":
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
So here's a complete working example:
_Layout.cshtml:
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div id="header">header</div>
<div id="main">#RenderBody()</div>
</body>
</html>
HomeController:
public class HomeController : Controller
{
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
ViewBag.Message = "partial";
return PartialView();
}
else
{
ViewBag.Message = "full";
return View();
}
}
}
Index.cshtml:
<script type="text/javascript">
$(function () {
$('#myLink').click(function () {
$.post(this.href, function (result) {
$('#main').html(result);
});
return false;
});
});
</script>
HomeController index. #ViewBag.Message
#Html.ActionLink("Index", "Index", new { controller = "Home" }, new { id = "myLink" } )
add
jQuery.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
});
to make sure the correct header is attached.

Resources