Simple ASP.NET PartialView issue - c#

I'm very new to ASP.Net and am trying to figure out partial views. I'm trying to get some very simple data to load in a partial view and am just not having any luck. I've got the following, and everything in it works except the load button:
Index.cshtml
#model IEnumerable<MMC_ASP.Models.MMCProjectViewModel>
#{
ViewBag.Title = "MMCView";
}
<h2>Active Projects</h2>
<div class="project-list">
#foreach (var item in Model)
{
<div class="mig-project #item.ColorClass">
<div>
<div class="client-name">#item.Client</div>
<div class="source-target">#item.SourceTarget</div>
<div class="server-name">#item.ServerName</div>
<div class="error-count">#item.ErrorCount</div>
</div>
</div>
}
</div>
<div id="partial"></div>
<input type="button" id="btn" value="Click for Data" />
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function () {
$('#partial').load('/MMC/LoadPartialView');
});
});
</script>
MMCController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MMC_ASP.Controllers
{
public class MMCController : Controller
{
public ActionResult Index()
{
Models.MMCProjectViewModel Project1 = new Models.MMCProjectViewModel() { Client = "Test Client1", SourceTarget = "Source to Target", ServerName = "Server1", ErrorCount = 3, ColorClass = "yellow" };
Models.MMCProjectViewModel Project2 = new Models.MMCProjectViewModel() { Client = "Test Client2", SourceTarget = "Source to Target", ServerName = "Server2", ErrorCount = 1, ColorClass = "red" };
Models.MMCProjectViewModel Project3 = new Models.MMCProjectViewModel() { Client = "Test Client3", SourceTarget = "Source to Target", ServerName = "Server3", ErrorCount = 0, ColorClass = "green" };
Models.MMCProjectViewModel Project4 = new Models.MMCProjectViewModel() { Client = "Test Client4", SourceTarget = "Source to Target", ServerName = "Server4", ErrorCount = 2, ColorClass = "green" };
Models.MMCProjectViewModel Project5 = new Models.MMCProjectViewModel() { Client = "Test Client5", SourceTarget = "Source to Target", ServerName = "Server5", ErrorCount = 1, ColorClass = "red" };
List<Models.MMCProjectViewModel> ProjectList = new List<Models.MMCProjectViewModel>();
ProjectList.Add(Project1);
ProjectList.Add(Project2);
ProjectList.Add(Project3);
ProjectList.Add(Project4);
ProjectList.Add(Project5);
return View(ProjectList.OrderBy(o => o.Client).ToList());
}
public ActionResult LoadPartialView()
{
return PartialView();
}
}
}
LoadPartialView.cshtml
<div>TEST DATA HERE</div>
Nothing happens when I click the "Click for Data" button. What am I missing? And for the record, I do realize I should be breaking the script into a separate file, and that the work on the Index action will be done differently. This is a proof of concept for me to make sure I understand all the pieces, and I believe this is the last one to make this work.

Your code looks fine. I have a very strong feeling that your code is failing to update the partial view because you are getting a 404 Not Found error when trying to make an ajax call.
It is a good practice to take advantage of the HTML helper methods like Url.Action to generate the correct url to an action method. You can execute the Url.Action method in the razor view and keep the output of that(the url) in html 5 data attributes on the button.
<input type="button" id="btn" data-url="#Url.Action("LoadPartialView","MMC")"
value="Click for Data" />
Now when click event happens, read the data attribute value and use that to make the ajax call.
$(function () {
$('#btn').click(function (e) {
e.preventDefault();
$('#partial').load($(this).data("url"));
});
});

Thanks to the great help from #sleeyuen, #Shyju, and #maccettura I got it working. I needed to add this to my view below the #{ViewBag.Title...} area:
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$('#btn').click(function (e) {
$('#partial').load($(this).data("url"));
});
});
</script>
}
And the Ajax.BeginForm method wouldn't work because my project doesn't include jquery.unobtrusive-ajax.js. Hope this helps someone else down the line.

Related

Return JSON with ajax is giving me blank page with return parameters

I started learning AJAX like this week and I was trying to make a simple voting thingy on page in asp mvc - when you click one button you get message like a popup (in browser) and count increments, when you click second, you get another count decrements, you get the idea.
I wanted to test it's possible to do like voting system (upvotes/downvotes) that will update itself's oount on click without needing to refresh the page.
However, when I click on this buttons, it gets me blank page with the things that return json contains. (picture included at the very bottom of post).
I am most likely missing something obvious, so please bear with me and if you could navigate me where am I wrong, please do.
My Controller:
public IActionResult Privacy()
{
Vote vote = new Vote();
vote.Votes = 0;
return View(vote);
}
[HttpPost]
public ActionResult VoteUp(string plus, string minus)
{
Vote vote = new Vote();
if (plus == null)
{
vote.Votes = vote.Votes -1;
var message = "You voted down";
return Json(new { success = true, message = message }, new Newtonsoft.Json.JsonSerializerSettings());
}
else if ((minus == null))
{
vote.Votes = vote.Votes +1 ;
var messagez = "You voted up";
return Json(new { success = true, message = messagez }, new Newtonsoft.Json.JsonSerializerSettings());
}
else { }
var messagebad = "STH WENT WRONG";
return Json(new { success = true, message = messagebad }, new Newtonsoft.Json.JsonSerializerSettings());
}
My View:
#model JSON_RETURN.Models.Vote
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#{
ViewData["Title"] = "sssss";
}
<form asp-action="VoteUp" asp-controller="Home" method="POST" data-ajax="true">
<div class="form-group"> </div>
<div class="input-group-button">
<button name="plus" class="btn btn-dark" onclick="" value="1" >+</button>
#Model.Votes
<button name="minus" class="btn btn-dark" onclick="" value="-1" >-</button>
</div>
</form>
#section scripts{
<script src="~/lib/ajax/jquery.unobtrusive-ajax.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
function SubmitForm(form) {
form.preventDefault();
$.ajax({
type: "POST",
url: "HomeController/VoteUp", //form.action,
data: ('#form'),
success: function (data) {
if (data.success) {
alert(data.message);
} else {
}
},
});
};
</script>
}
My Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace JSON_RETURN.Models
{
public class Vote
{
public int Votes { get; set; }
}
}
And there's the blank page I'm getting every click (message varies ofc):
(https://imgur.com/uVNSmE6)
What you did is just a form submit instead of using ajax. Why it return json string that is because you return json string in your backend code(return Json(new { success = true, message = messagebad }, new Newtonsoft.Json.JsonSerializerSettings());).
I saw you use jquery.unobtrusive-ajax.js in your code, also you create a js function with ajax. Actually, you just need to choose one of the two ways to achieve your requrement.
Here is the correct way of using jquery.unobtrusive-ajax.js :
Note:
1.If you use asp.net core, it contains jquery.js in _Layout.cshtml by default. So when you use #section Scripts{}, no need add the jquery.js again. If your _Layout.cshtml does not contain jquery.js, you need add this js file before jquery.unobtrusive-ajax.js:
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/ajax/jquery.unobtrusive-ajax.js"></script>
2.You need specific data-ajax-update to tell the elements where need to be updated with the AJAX result.
More supported data attributes for jquery.unobtrusive-ajax.js you can refer to here.
View:
#model Vote
#addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
#{
ViewData["Title"] = "sssss";
}
<div id="result"> //add this div...
//add this...
<form asp-action="VoteUp" asp-controller="Home" method="POST" data-ajax-update="#result" data-ajax="true">
<div class="form-group"> </div>
<div class="input-group-button">
<button name="plus" class="btn btn-dark" value="1">+</button>
#Model.Votes
<input hidden asp-for="Votes" /> //add this....
<button name="minus" class="btn btn-dark" value="-1">-</button>
</div>
</form>
</div>
#section scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ajax-unobtrusive/3.2.6/jquery.unobtrusive-ajax.js" integrity="sha256-v2nySZafnswY87um3ymbg7p9f766IQspC5oqaqZVX2c=" crossorigin="anonymous"></script>
}
Controller:
Note: You can see that I add a hidden input for Votes in form, that is because only input or select type of element can be post to backend. The reason for why I want to get Votes value is because your code always create a new instance for Vote, the value will always plus start with 0.
public IActionResult Privacy()
{
Vote vote = new Vote();
vote.Votes = 0;
return View(vote);
}
[HttpPost]
public ActionResult VoteUp(string plus, string minus)
{
Vote vote = new Vote();
vote.Votes = int.Parse(Request.Form["Votes"]);
if (plus == null)
{
vote.Votes = vote.Votes - 1;
}
else if ((minus == null))
{
vote.Votes = vote.Votes + 1;
}
else { }
return PartialView("Privacy", vote);
}
Result:

jQueryu ui autocomplete doesn´t show anything in MVC c#

I want to display an autocomplete textbox in a MVC C# View using jQuery-ui autocomplete, this is the code of my view
#{
ViewBag.Title = "Index";
}
<script src ="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript">
$(function () {
$("#SearchString").autocomplete({
source: "/Borrar/autocompletar",
minLength: 1,
select: function (event, ui) {
if (ui.item) {
$("#SearchString").val(ui.item.value);
}
}
});
});
</script>
<div class="container col-md-10 col-md-offset-3">
<h2>Autocompletar</h2>
#using (Html.BeginForm())
{
<p>
Empresa: #Html.TextBox("SearchString")
<input type="submit" value="Search" />
</p>
}
</div>
this is the code of the controller that should populate the textbox
public JsonResult autocompletar(string prefix)
{
List<GFC_Site.ViewModels.EmpresaAutocomplete> listado = new List<GFC_Site.ViewModels.EmpresaAutocomplete>();
ProxyGFC.ServiceGFCClient cliente = new ProxyGFC.ServiceGFCClient();
List<WcfService.Entidades.EmpresaAutocomplete> listadoBase = new List<WcfService.Entidades.EmpresaAutocomplete>();
listadoBase = cliente.Autocompletar(prefix);
foreach (var item in listadoBase)
{
GFC_Site.ViewModels.EmpresaAutocomplete dato = new ViewModels.EmpresaAutocomplete();
dato.empresa = item.empresa;
//dato.np = item.np;
listado.Add(dato);
}
return Json(listado, JsonRequestBehavior.AllowGet);
}
where (GFC_Site.ViewModels.EmpresaAutocomplete) is a class with only one string property (empresa) and (ProxyGFC.ServiceGFCClient cliente) is a connection to a WCF Server, the WCF is the one that connects the application with the database and (List listadoBase) is a class in WCF with two properties(empresa and np).
and this is the method in WCF that retrieve the info that I want to display in the textbox
public List<EmpresaAutocomplete> Autocompletar(string prefix)
{
OdbcCommand cmd = Helper.Commandos.CrearComando();
cmd.CommandText = "select numero_patronal, nombre_empresa from empresas where estado= ? and nombre_empresa like ?";
cmd.Parameters.Add("#estado", OdbcType.VarChar).Value = "1";
cmd.Parameters.AddWithValue("#empresa", prefix + "%");
List<EmpresaAutocomplete> data = new List<EmpresaAutocomplete>();
try
{
cmd.Connection.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
EmpresaAutocomplete datos = new EmpresaAutocomplete();
datos.np = reader["numero_patronal"].ToString();
datos.empresa = reader["nombre_empresa"].ToString();
data.Add(datos);
}
}
catch (Exception ex)
{
throw new ApplicationException("Excepcion :", ex);
}
return data;
}
well, my problem is that the textbox doesn´t show anything, actually it gets frozen
could you please tell me what seems for you to be the problem?
First off, let’s take take a look at autocomplete in action, starting with a text input:
<label for=”somevalue”>Some value:</label><input type=”text” id=”somevalue” name=”somevalue”/>
If we add a reference to the jQuery UI script file and css file, we can add a script block to our view:
<script type=”text/javascript” language=”javascript”>
$(document).ready(function () {
$(‘#somevalue’).autocomplete({
source: ‘#Url.Action(“Autocomplete”)’
});
}) </script>
This script block identifies the text input by id and then invokes the autocomplete function to wire up the autocomplete behaviour for this DOM element. We pass a URL to identify the source of the data. For this post I’ve simply created an ASP.NET MVC action that returns JSON data (shown below). Note that in the view I used Url.Action to look up the URL for this action in the routing table – avoid the temptation to hard-code the URL as this duplicates the routing table and makes it hard to change your routing later.
public ActionResult Autocomplete(string term)
{
var items = new[] {“Apple”, “Pear”, “Banana”, “Pineapple”, “Peach”};
var filteredItems = items.Where(
item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
);
return Json(filteredItems, JsonRequestBehavior.AllowGet);
}
https://blogs.msdn.microsoft.com/stuartleeks/2012/04/23/asp-net-mvc-jquery-ui-autocomplete/

How to Implement Autocomplete Textbox in MVC

I am facing a problem in autocompleting the textbox vith hardcoded data, my json "Search" method does not fire i have been search a lot of code implement it into my project but did not get any success yet. i dont know where is the problem. kindly help me thankx in advance
Model:
public class Locations
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller:
public JsonResult Search(string query)
{
List<Locations> locations = new List<Locations>()
{
new Locations() {Id = 1, Name = "London"},
new Locations() {Id = 2, Name = "Walles"},
new Locations() {Id = 3, Name = "Birmingham"},
new Locations() {Id = 4, Name = "Edinburgh"},
new Locations() {Id = 5, Name = "Glasgow"},
new Locations() {Id = 6, Name = "Liverpool"},
new Locations() {Id = 7, Name = "Bristol"},
new Locations() {Id = 8, Name = "Manchester"},
new Locations() {Id = 9, Name = "NewCastle"},
new Locations() {Id = 10, Name = "Leeds"},
new Locations() {Id = 11, Name = "Sheffield"},
new Locations() {Id = 12, Name = "Nottingham"},
new Locations() {Id = 13, Name = "Cardif"},
new Locations() {Id = 14, Name = "Cambridge"},
new Locations() {Id = 15, Name = "Bradford"},
new Locations() {Id = 16, Name = "Kingston Upon Hall"},
new Locations() {Id = 17, Name = "Norwich"},
new Locations() {Id = 18, Name = "Conventory"}
};
List<string> Loc;
Loc = locations.Where(x => x.Name.StartsWith(query.ToLower())).Select(x => x.Name).ToList();
return Json(Loc, JsonRequestBehavior.AllowGet);
}
View:
#model IEnumerable<SearchBox.Models.Locations>
#using SearchBox.Models
#{
ViewBag.Title = "Index";
}
<link href="~/Content/Autocomplete/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/Autocomplete/jquery-ui.js"></script>
<link href="~/Content/Autocomplete/jquery-ui.theme.css" rel="stylesheet" />
<script type="text/javascript">
$("#tags").autocomplete({
source: '#Url.Action("Search")'
});
</script>
<input type="text" id="tags" />
You need to make ajax request instead of passing just url in data source.
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script src="~/Content/jquery-1.12.4.js"></script>
<script src="~/Content/jquery-ui.js"></script>
<input type="text" id="tags" />
<script type="text/javascript">
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("Search")',
dataType: "jsonp",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Id
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
}
});
</script>
See how to use autocomplete with ajax request.
I have implemented this in my project. Please check if you can make use of it
<div class="tag_cover" style="margin-top:60px; margin-left:57px">
<input type="text" style="width:300px; display:inline-block; border:transparent" class="tag_input brzero has-icon" id="SkillSet" list="json-datalist" placeholder="Employee name or Skills">
<datalist id="json-datalist"></datalist>
</div>
JQuery:
$(".tag_input").keyup(function (e) {
var type = $("input[name='search']:checked").val();
if (type == "Name") {
var sString = $("#SkillSet").val();
if (sString == null || sString == "") {
e.preventDefault();
}
else {
$.ajax({
url: "#Url.Action("GetEmployeeNameByKeyword","Home")",
type: "POST",
data: { 'SearchedString': sString },
dataType: "json",
success: function (data) {
if (data == null || data == "") {
//alert("no skills found");
}
else {
var dataList = document.getElementById('json-datalist');
$(dataList).empty();
$.each(data, function (key, value) {
$(dataList).append($('<option>').text(value.UserNames.trim()).attr("value", value.UserId));
});
}
},
error: function () {
alert("failure");
}
});
}
}
}
Controller:
public JsonResult GetEmployeeNameByKeyword(string SearchedString)
{
List<UserProfile> EmployeeNames = new List<UserProfile>();
EmployeeNames = _db.UserProfiles.Where(i => i.UserNames.Contains(SearchedString)).ToList();
return Json(EmployeeNames, JsonRequestBehavior.AllowGet);
}
I have been looking everywhere for references on a feature like this, myself.
I don't have enough rep to comment, but Naveen's answer worked for me after I started going one line at a time with console.log("PASS");. If the function is never called on an event like keyup, then it likely means one of the variable names is wrong or there is bad syntax. The reason you could not get any calls to the javascript was because of a missing }); which is an ending statement for JQuery functions. The end of the code for the scripting part should appear like so:
}
}); //END $.ajax
}
}
}); //END keyup function
Using Razor, with T4MVC at an MVC5 project, we'll implement jQuery Autocomplete.
You should have inside your solution, one or more projects, and inside your project, among many other usual MVC5 things, the folders Models, Views and Controllers. And inside of them...
NuGet
Get the dependencies in place (your should know how to get them using Visual Studio):
jQuery: https://www.nuget.org/packages/jQuery/3.6.0
jQuery-UI: https://www.nuget.org/packages/jQuery.UI/
Then put them in the BundleConfig.cs files, at the App_Start folder:
using System.Web.Optimization;
namespace MyProject.Web
{
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles
.Add(new ScriptBundle("~/bundles/jquery")
.Include(
"~/Scripts/jquery-{version}.js",
"~/Scripts/jquery-ui.js",
));
bundles
.Add(new StyleBundle("~/Content/css")
.Include(
"~/Content/jquery-ui.css"
));
}
}
}
This will add the dependencies you´ll need to the view (see View section down below for more instructions).
Model
namespace MyProject.Web.Models.MyModelFolder
{
public class MyModel
{
public string MyValue { get; set; }
public string MyAnotherValue { get; set; }
public string AndAnotherValue { get; set; }
}
}
View
(Using Bootstrap)
#model MyProject.Web.Models.MyModelFolder.MyModel
<div class="ui-widget">
#Html.LabelFor(model => model.MyValue)
#Html.EditorFor(model => model.MyValue, new { htmlAttributes = new { #class = "form-control", id = "myTextbox" } })
#Html.ValidationMessageFor(model => model.MyValue, "", new { #class = "text-danger" })
</div>
We'll be querying the MyValue field.
And add the dependencies from the BundleConfig.cs where you'll need them in your page:
<header>
#Styles.Render("~/Content/css")
</header>
<body>
<p>Your Content</p>
#Scripts.Render("~/bundles/jquery")
</body>
Adding the Autocomplete
There are two ways you can accomplish this, as:
Internal file to the page or,
as an external .js file.
NOTE: Autocomplete must be always below the required jQuery dependencies.
Internal file
In the .cshtml file. Inside your <body> tag, at the bottom of it:
<script>
$("#myTextbox").autocomplete({
source: '#Url.Action(MVC.MyController.MyMethod())'
});
</script>
Or instead in the...(Choose one, not both!)
External file
In the Scripts folder. Remember to add this block at the bottom of your view to call the function from the outside.
#section Scripts {
<script src="~/Scripts/autocomplete.js"></script>
}
And in the Scripts folder in a JS file add:
$(document).ready(function () {
$("#myTextbox").autocomplete({
source: '/MyController/MyMethod',
});
})
You can see there the method you'll be calling from from the controller.
Controller
#region jQuery Method Calls
using MyProject.Web.Models.MyModelFolder;
public virtual JsonResult MyMethod(string term)
{
// _myViewModel is a partial model
List<MyModel> MyAutocompleteList = new List<MyModel>();
/* In this example I´m using AutoMapper, and getting back the List
from the Database (layer, using Entity Framework), using Repository
Pattern (layer) and Unit of Work Pattern. */
// But you can get the List however way you want.
MyAutocompleteList = _theMapper.GetMyModelList(_operationsLayerService.GetMyModelList());
// This LINQ query makes the magic happen
var result = from U in MyAutocompleteList
where U.MyValue.Contains(term)
// It retrieves a composed string, not just a single value.
select new { value = $"{U.MyValue} | {U.MyAnotherValue} {U.AndAnotherValue}" };
// Security vulnerabilities? https://stackoverflow.com/a/21453075/7389293
return Json(result, JsonRequestBehavior.AllowGet);
}
#endregion
That's it.

How to combine between the script and the action in the button

I am developing an ASP .Net MVC 3 application using C# and SQL Server 2005.
In a view, I have a button which I add in it a JQuery Script.
This button has as purpose to save some values in a list.
The problem that the button works perfectly but when i add the Script, the situation change and the button didn't works and became static (dead).
This is the code in the view :
<div>
<input type="submit" value="Enregistrer" id="btnSave" />
</div>
<script type="text/javascript">
$(function () {
$('#btnSave').click(function () {
$('#poste option:selected').remove();
return false;
});
});
</script>
and this is the code of methode save in the controller :
[HttpPost]
public ActionResult Save(FlowViewModel model)
{
Console.WriteLine("" + model.Nbr_Passage);
if (ModelState.IsValid)
{
Gamme G = new Gamme();
G.ID_Gamme = model.SelectedProfile_Ga;
G.ID_Poste = model.SelectedPoste;
//G.Last_Posts = model.PostePrecedentSelected;
G.Next_Posts = model.PosteSuivantSelected;
G.Nbr_Passage = int.Parse(model.Nbr_Passage);
G.Position = int.Parse(model.Position);
((List<Gamme>)System.Web.HttpContext.Current.Session["GammeList"]).Add(G);
var list = ((List<Gamme>)System.Web.HttpContext.Current.Session["GammeList"]);
}
return RedirectToAction("Index");
}
Remove return false; from your script:
$(function () {
$('#btnSave').click(function () {
$('#poste option:selected').remove();
});
});

something wrong in view page and url

I am using c# and ASP.NET MVC4 for a web application (with mobile template).
I'm having a problem with my Details view page. (First you select something from Index page and then it goes to Details page) I have put a bing map on the page and the map doesn't load.
First I thought it was something wrong with the map but its not.
I noticed that the url is
http://localhost:2550/Place/Details
of the page. However if I manually put a '1' on the end like so http://localhost:2550/Place/Details/1
then the map loads on the page. I don't understand why this is...
does anyone know why? thanks
my view page for Details:
#model Project.Models.Place
#{ ViewBag.Title = "Details";}
<h2>Place Details</h2>
<fieldset>
<div class="display-label"> Name: #Model.Name</div>
<div class="display-label">Address: #Model.Address</div>
<div class="display-label">Post Code: #Model.PostCode</div>
<div class="display-label"> PhoneNo: #Model.PhoneNo</div>
</fieldset>
<p> #Html.ActionLink("Back to List", "Index")</p>
<body onload="getMap();">
<div id='myMap' style="position:relative; width:400px; height:400px;"></div>
<div>
<input type="button" value="createWalkingRoute" onclick="createDirections();" />
</div>
<div id='directionsItinerary'> </div>
</body>
#section scripts{
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var directionsManager;
var directionsErrorEventObj;
var directionsUpdatedEventObj;
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'mykey' });
}
function createDirectionsManager() {
var displayMessage;
if (!directionsManager) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
displayMessage = 'Directions Module loaded\n';
displayMessage += 'Directions Manager loaded';
}
alert(displayMessage);
directionsManager.resetDirections();
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { alert(arg.message) });
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { alert('Directions updated') });
}
function createWalkingRoute() {
if (!directionsManager) { createDirectionsManager(); }
directionsManager.resetDirections();
// Set Route Mode to walking
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.walking });
var seattleWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Seattle, WA' });
directionsManager.addWaypoint(seattleWaypoint);
var redmondWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Redmond, WA', location: new Microsoft.Maps.Location(47.678561, -122.130993) });
directionsManager.addWaypoint(redmondWaypoint);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
function createDirections() {
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createWalkingRoute });
}
else {
createWalkingRoute();
}
}
</script>
}
my controller action for Details:
public ViewResult Details(int id)
{
ViewBag.events = eventRepository.PlaceEvents(id);
return View(placeRepository.Find(id));
}
Possible cause, may be you haven't written Controller default controller with Zero arguments.
Or you haven't written controller with [HttpPost] attribute
Will be easy if you put code for the controller here.
If you say that the navigation with /1 at the end works but your current url is without the number, your url on the index page is wrong.
Your url is now something like
#Html.ActionLink("Details", "Place")
Change it to something like this:
#Html.ActionLink("Details", "Place", new { id = #Model.Id })
So the problem is that your id isn't given to your details action.

Categories