Я использую Visual Studio 2017 для написания своего веб-приложения MVC 5.Недавно я столкнулся с очень необычной ошибкой в моем проекте.Я решил проблему, но мне хотелось бы знать, почему это так работает?
Я изменяю атрибут href
тега <link>
динамически в $(document).ready()
.Когда я делаю это, маршрут MVC по умолчанию вызывается излишне только в IE11, в других браузерах это не происходит.Чтобы решить эту проблему, мне пришлось удалить атрибут href
, как показано в _Layout.cshtml
ниже.Я хочу знать, почему это работает?
Я создал минимальный проверяемый код, который приведен ниже.
RouteConfig.cs:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "NCB", action = "Index", id = UrlParameter.Optional }
);
}
}
NCBController.cs:
public class NCBController : Controller
{
public ActionResult Index()
{
Session.Abandon();
return View();
}
[HttpPost]
public ActionResult Index(FormCollection form)
{
Session["LoggedIn"] = "true";
return RedirectToAction("Page2");
}
public ActionResult Page2()
{
var isLoggedIn = Session["LoggedIn"].ToString();
return View();
}
[HttpPost]
public ActionResult Page2(FormCollection form)
{
var isLoggedIn = Session["LoggedIn"].ToString(); //Place where session is empty only in IE11 because GET:Index() was called
return View();
}
}
_NCBLayout.cshtml:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>_NCBLayout</title>
<link href="" rel="stylesheet" class="oldlink" /> <!--Calls default MVC route if I use this line-->
<link rel="stylesheet" class="oldlink" /> <!--Does not call default MVC route if I use this line-->
</head>
<body>
<div>
@RenderBody()
</div>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var oldlink = document.getElementsByClassName("oldlink").item(0);
var newlink = document.createElement("link");
newlink.setAttribute("rel", "stylesheet");
newlink.setAttribute("type", "text/css");
newlink.setAttribute("href", '@Url.Content("~/Content/bootstrap.css")');
newlink.setAttribute("class", "oldlink");
document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink); //I think this line is calling the default MVC route
});
</script>
</body>
</html>
Index.cshtml:
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_NCBLayout.cshtml";
}
<h2>Index</h2>
@using(Html.BeginForm("Index", "NCB"))
{
<button type="submit">Submit</button>
}
Page2.cshtml:
@{
ViewBag.Title = "Page2";
Layout = "~/Views/Shared/_NCBLayout.cshtml";
}
<h2>Page2</h2>
@using (Html.BeginForm("Page2", "NCB"))
{
<button type="submit">Next</button>
}