Reputation: 793
I have modified the Map Route in my Dot Net Core application that for every request goes to one controller, so not lots of controller or Action Result is needed for each page that we build.
routes.MapRoute("", "/{*article}",
defaults: new { controller = "Pages", action = "Killme" });
In Page Controller build an object that has list of CSS and JavaScript locations, this object is being passed to Page view
public IActionResult Killme()
{
var PageInfo = GetPage_Data();
ViewBag.PageInfo = t;
return View("Pages");
}
and i have tried to pass this information as model or view bag to Page view. in the Page view i try to build the JavaScript and CSS dynamically based on the model like
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
@{
RootObject PageInfo = ViewBag.PageInfo;
foreach (var JavaScript in PageInfo.js)
{
var JSsrc = JavaScript.src;
<script type="text/javascript" src="@JSsrc ">
</script>
}
<script type="text/javascript" src=""></script>
</head>
<body>
</body>
</html>
Now the Issue is when i build the JavaScript the controller is called 2 times and the page is being rendered 2 times, when i comment the
<script type="text/javascript" src="@JSsrc ">
</script>
the page controller will get called once, any help regarding why this happening and what am i doing wrong would be appreciated
Upvotes: 0
Views: 61
Reputation: 7125
The reason for this behavior is that the staticFileHandler is either not configured or is not able to find your Javascript file and passes the request further down the pipeline. The MVC handler captures all requests (because of your route) and returns therefore the same page again.
First check that your startup class uses the staticFileHandler before the mvcHandler, so something like this:
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseStaticFiles();
..
app.UseMvc();
}
}
Secondly make sure that your Javascript is placed inside the wwwroot and uses the correct path.So a file like wwwroot/js/mysite.js should a script tag like:
<script src="/js/mysite.js"></script>
These improvements should resolve your issue.
Upvotes: 1