How do I set dropdown option selected by looking at MVC URL

Hello and thank you for making stackoverflow such a great resource for learning programmers like me. I've been reading lots of answers on here to help with my first MVC project, this is my first time asking.

Here is my dropdown HTML

<div class="dropdown">
    <select id="assetSelect" onchange="location = this.options[this.selectedIndex].value;">
        <option value="/History/Index/All">All Assets</option>
        @foreach (var item in Model.NodeInfo)
        {
            <option value="/History/Index/@item.node.name">@item.node.name</option>
        }
    </select>
</div>

Once an item is selected from the dropdown, the url will look like this

http://web.site/History/Index/G0000106

Now I'm trying to grab that last part of the URL (in this case G0000106) and set the corresponding dropdown option to selected. Here is the javascript I have pieced together so far but it's not working.

$('#assetSelect').find('option').each(function () {
    function getCurrentPageId() {
        var params = window.location.href.split('/');
        var i = params.length;
        var pageId = params[i];
        return pageId;
    }
    var currentPageId = getCurrentPageId();
    var $this = $(this);
    if ($this.text() == currentPageId) {
        $this.attr('selected', 'selected');
        return false;
    }
});

Will this function work with the one that populates the dropdown list? Is this the best way or is there an HTML helper that can do it? Any help is appreciated, thanks!

Answers:

Answer

Option 1. You can simplify your code significantly:

function getCurrentPageId() {
    var params = window.location.href.split('/');
    return params[params.length - 1];
}

var pageId = getCurrentPageId();
$('#assetSelect').find('option:contains(' + pageId + ')').prop('selected', true);

Anyway, your problem was in this line:

var i = params.length;
var pageId = params[i];

It should be params[i - 1], since you want to get the last array element.

Option 2. An even simpler approach which should also work for you is to use location.pathname:

$('#assetSelect').val(window.location.pathname);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.