I'm trying to make a simple DropDownList (something that is simple and fun in c# but somehow frustrating in this context) to allow me to navigate around my MVC App.
I'm not experienced with JavaScript at all, but I've spent most of the day trying all sorts of things and using Chrome's JavaScript Console to try and troubleshoot what I can.
This is what I've boiled it down to.
Razor Engine View:
<h2>Index</h2>
<p>
@Html.DropDownList("DDLRegion", new SelectList(ViewBag.Tables), new { @id = "DDLRegion" }) <br />
@Html.ActionLink("Area1", "Index", "Area1") <br />
@Html.ActionLink("Area2", "Index", "Area2") <br />
@Html.ActionLink("Area3", "Index", "Area3") <br />
</p>
@section Scripts{
<script src="/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$("#DDLRegion").change(function () {
var selectedItem = $(this).val();
switch (selectedItem) {
case '0':
window.location.href = @Url.Action("Index", "Area1");
break;
case '1' :
window.location.href = @Url.Action("Index", "Area2");
break;
case '2' :
window.location.href = @Url.Action("Index", "Area3");
break;
default:
window.location.href = @Url.Action("Index", "Area1");
alert("Blarg");
break;
}
});
</script>
}
window.location.href = @Url.Action("Index", "Area1");
this would be rendered as window.location.href=sitePrefix/Area1/Index;
Now, window.location.href=sitePrefix/Area1/Index;
is not a valid javascript statement. the RHS of expression should be a proper value. Since this is a URL, you can treat it as string.
window.location.href = '@Url.Action("Index", "Area1")';
appending single quotes around the RHS will work.