0

I'm trying to replicate the answer found below: is it posible do have Html.ActionLink inside a DropDownList Without java script?

@Html.DropDownList(
    "url",
    new SelectList(new[]
    {
        new SelectListItem { Text = "Home", Value = Url.Action("Home", "Home") },
        new SelectListItem { Text = "About", Value = Url.Action("About", "Home") },
        new SelectListItem { Text = "Contact", Value = Url.Action("Contact", "Home") },
    }, "Value", "Text"),
    "Change View",
    new { id = "urlddl" }
)

$(function() {
    $('#urlddl').change(function() {

        var url = $(this).val();
        if (url != null && url != '') {
            window.location.href = url;
        }
    });
});

The problem is, when i select an item in the DropDownList, nothing happened. Any help is greatly appreciated.

Edit: I've edit it to what it was suppose to be. I edit the code and paste the wrong one.

Kidan
  • 1
  • 1
  • `var text = $(this).find('option:selected').text();` –  Apr 01 '18 at 22:32
  • But what is the point? And your `if/else` block makes no sense - you already have the url by using `$(this).val()` - just follow the code in the link you included in the question and use `location.href` to redirect –  Apr 01 '18 at 22:37
  • Your current code generates invalid script! (check view source of the rendered page). All you need is this one line in the change event handler `location.href=$(this).val();` – Shyju Apr 01 '18 at 22:38
  • Sorry that was typo. I changed it afterward and paste the wrong code it was originally : window.location.href = url; – Kidan Apr 01 '18 at 22:52
  • @Shyju I've tried location.href instead of window.location.href and same problem – Kidan Apr 01 '18 at 22:58
  • Use `$(this).val()` which will give you the value attribute value of the selected option (which has the url ) – Shyju Apr 01 '18 at 22:59
  • Thanks maybe i had a type somewhere earlier so it didnt work. it's working now – Kidan Apr 01 '18 at 23:02

0 Answers0