[英]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. 您好,感谢您使stackoverflow成为学习像我这样的程序员的好资源。 I've been reading lots of answers on here to help with my first MVC project, this is my first time asking.
我一直在这里阅读很多答案,以帮助我进行第一个MVC项目,这是我第一次问。
Here is my dropdown HTML 这是我的下拉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 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. 现在,我尝试获取URL的最后一部分(在本例中为G0000106),并将相应的下拉选项设置为selected。 Here is the javascript I have pieced together so far but it's not working.
到目前为止,这是我拼凑的JavaScript,但是无法正常工作。
$('#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?
这是最好的方法还是有HTML助手可以做到? Any help is appreciated, thanks!
任何帮助表示赞赏,谢谢!
Option 1. You can simplify your code significantly: 选项1.您可以大大简化代码:
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. 它应该是
params[i - 1]
,因为您要获取最后一个数组元素。
Option 2. An even simpler approach which should also work for you is to use location.pathname
: 选项2。一种更简单的方法(也应该对您有用)是使用
location.pathname
:
$('#assetSelect').val(window.location.pathname);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.