MVC website- On the home page header section, I have a drop down with two options in it. Each option should route to a different Controller/ActionMethod. Since I need this to be in a header section of every page, I put this in the site.master file.
Dropdown code :
<%=Html.DropDownList("OneOrTwo",
new List<SelectListItem>
{
new SelectListItem{ Text="One", Value = "One" },
new SelectListItem{ Text="Two", Value = "Two" }
}
, new { @style = "background-color:#f00; border: none;", onchange =
"fnNum()" }
)%>
In the javascript file, I have this that routes to different controller/action method based on the drop down selection.
function fnNum()
{
var e = document.getElementById("OneOrTwo");
var SelValue = e.options[e.selectedIndex].value;
if (SelValue == "One")
window.location.href = "Controller1/Index";
else
window.location.href = "Controller2/Index";
}
There are two issues with this approach :
-
When selection is changed – the newly selected option does not retain. The drop down switches back to original choice even if the web page is showing the new controller/action method view…
-
On subsequent selections of the same choice – takes me to localhost:/Controller1/Index/Controller1/Index/etc….. there has to be a clean way to do this.
So I want two things :
- A changed selection should be retained.
- On subsequent selections, the control needs to be routed properly to controller/index every time and not to controller/index/controller/index…etc..
Thanks for the help.
To fix problem 1, you have to set the
Selectedproperty of yourSelectListItems. So I would change your code to generate the drop-down to something like this:The second problem is easier to solve. It comes from the fact that you’re setting the window location to relative, not absolute URLs. Just change it to: