I have a simple phonebook app that allows the user to search for an employee via a dropdown list of departments or by name via text input. The way I'm handling the search is simply changing the action attribute of the html form with javascript based on whatever they typed or whichever option they selected in the dropdown:
function selectedOption(option) {
var selValue = option.value;
document.getElementById("search-form").action = "/home/index/" + selValue;
}
This works on localhost but when I host it on IIS:
machineName/appName
becomes
machineName/home/index/selValue
cutting off the app name and returning a 404 error
The only way I've been able to get around this is with some hardcoding to check whether "home/index" exists in the path already...
function selectedOption(option) {
var selValue = option.value;
if (window.location.href.includes("home")) {
var searchDest = selValue
} else {
var searchDest = window.location.href + "/home/index/" + selValue
}
document.getElementById("search-form").action = searchDest;
}
This works but it is not very clean or conventional. Is there some way I can have the app name configured in Startup.cs? I saw the same issue in another question here but I'm getting syntax errors when I try to add another MapRoute. This is all that I currently have:
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
Any idea how to get around this?
as mentioned above by @Desmond Chin
, for cshtml
you can use HTML
helpers. I think the best one for that case is to use @Url.Action(actionName, controllerName)
instead @Url.Content()
- which is used for js
, css
, img
, etc..
You can use this code bellow to achieve this:
function selectedOption(option) {
var selValue = option.value;
document.getElementById("search-form").action = '@Url.Action("Index", "Home")?<<VARIABLENAMEHERE>>'+selValue;
}
The Html Helper will take care of your url, virtual paths and etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.