Simon Fletcher Simon Fletcher - 1 year ago 45
Javascript Question

Why can't I get my DropDownList change event work?

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:


@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 />

@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");
case '1' :
window.location.href = @Url.Action("Index", "Area2");
case '2' :
window.location.href = @Url.Action("Index", "Area3");
window.location.href = @Url.Action("Index", "Area1");

The latest error from the JavaScript console is complaining about missing a / on the case '0' block for the @Url.Action method (translates to end up as '/Area1').

Answer Source

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.