MVC Routing - Url not updating to new route - asp.net-mvc

I have the following MVC route:
routes.MapRoute("AccountLookupDirect",
"{culture}/account/{originalSellerId}/{accountNumber}",
new {culture = "en-gb", controller = "accountlookup", action = "index", originalSellerId = UrlParameter.Optional, accountNumber = UrlParameter.Optional},
new {culture = #"[a-z]{2}-[a-z]{2}"}
);
I can browse to a url such as http://{server}/**account**/{seller}/{accountnumber} and the page loads as expected. The problem is that when links are generated on a page, the url is not updating to the new route. Instead I get http://{server}/**{controller}**/{seller}/{accountnumber}.
The links are generated dynamically using Handlebars templating. The template looks like:
<script type="text/x-handlebars-template" data-template-name="account-link">
{{ AccountNumber }}
</script>
I have deployed the same code on two different servers and it works as expected on one, but not the other.

It seems that the cause of this issue was because the servers have a different version of the .NET framework installed. The working server has .NET 4.5 whereas the other only has .NET 4.
Unfortunately as we couldn't install 4.5 on one of the boxes we had to implement a very ugly workaround:
<script type="text/x-handlebars-template" data-template-name="account-link">
{{ AccountNumber }}
</script>

Related

ASP.NET Core 3.1 MVC Routing issue with IIS Default Web Site

New information:
After much messing around with trying to manipulate the URL I almost got it working but not quite. Then I discovered that it works without any coding changes if my home page url is \\localhost\ABIAdmin\Home. But it starts as \\localhost\ABIAdmin, and I have link in my _Layout to bring me there and it also comes up as \\localhost\ABIAdmin (without the \Home). It's easy enough to require our users to provide the full url with home in it, but I need the link to also provide \Home in it. Here's the html for the Home link:
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Dashboard</a>
So now the question is how do I get \Home in the url from the link, and if possible on startup? Can this be addressed through IIS, or through my endpoints?
I have an ASP.NET Core 3.1 MVC application with Razor Pages which works fine when I deploy it to IIS if I do not use the Default Web Site, or if I run the application as an exe. All of my navigation works, and all of my CRUD operations work (I'm using Syncfusion's DataGrid). However, if I deploy to the Default Web Site I run into what seem to be routing issues. Please note the following:
I added a folder under c:\inetpub\wwwroot called ABIAdmin, which contains my core app.
Relevant code from Startup/ConfigureServices: services.AddControllersWithViews();
Relevant code from Startup/Configure:
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseCookiePolicy();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "Privacy",
pattern: "{controller=Privacy}/{action=Privacy}/{id?}");
});
I have about 80 controllers not including the Privacy and Home controllers. There is no routing information in any of the controllers.
I tried messing with adding virtual directories but that did not help.
When I navigate to the Campaigns page from the Privacy page it forms a proper URL, e.g., http://localhost:5000/ABIAdmin/Campaigns, where ABIAdmin is the name of the site under the Default Web Site. But if I navigate from the Home page I get a 404 error. The requested URL is formed as http://localhost:5000/Campaigns, but it is missing the "/ABIAdmin", and the physical path is wrong too: C:\inetpub\wwwroot\Campaigns. When I successfully navigate from the Privacy page, the data is retrieved, but if I try to perform an Add/Update/Delete operation it just hangs. I believe this is because whatever URL the grid is forming is wrong. I don't think this is the fault of the Syncfusion grid.
So the question is, why does the Default Web Site behave differently then a standalone web site in this situation? We will be deploying this to multiple customers, and some will want it under the Default Web Site.
Any help would be appreciated. :)
It's looks like I found an answer. I have 3 scenarios to handle, running from VS, running from a standalone website, and running from an application under the Default Web Site. I could not figure out a way to tell in my _Layout.cshtml whether it is running under the Default Web Site so I'm using a configuration parameter to tell me that. I can tell whether I'm running from VS by the name of the application pool (from VS it's "ABIAdminApp AppPool"). I can also tell if I'm coming from the Home page now (that was the missing link), by checking Context.Request.Path. Given that info I can conditionally add the name of my application, ABIAdminApp. Note in the original post I may have referred to this as ABIAdmin. I will consider making the name of the app a configuration parameter as well.
#{
#using ABIAdminApp.Classes;
#using Microsoft.Extensions.Configuration;
#inject IConfiguration Configuration;
string appPoolId = System.Environment.GetEnvironmentVariable("APP_POOL_ID");
string appName = "";
if (appPoolId != "ABIAdminApp AppPool" && Context.Request.Path.ToString() == "" && Extensions.UseDefaultWebsite(Configuration)) { appName = "ABIAdminApp" + "/"; } else { appName = ""; }
string anchor_template = "<a href='" + appName + "${URL}'>${FriendlyName}</a>";
}
So that solves my navigation problems. I also had to make changes for the Syncfusion grid updates. I had to conditionally add the app name and used ViewBag for that purpose with dynamic values for insertUrl, updateUrl, and removeUrl.
So in my Index method of the controller for Campaigns I had this code (preceded by logic to determine whether or not to add the app name):
ViewBag.InsertUrl = AppName + "/Campaigns/Insert";
ViewBag.UpdateUrl = AppName + "/Campaigns/Update";
ViewBag.RemoveUrl = AppName + "/Campaigns/Delete";
And this code in my view, Campaigns.cshtml:
<e-data-manager url="Campaigns/Campaigns" adaptor="UrlAdaptor" insertUrl="#ViewBag.InsertUrl" updateUrl="#ViewBag.UpdateUrl" removeUrl="#ViewBag.RemoveUrl"></e-data-manager>

Using VueJS in a ASP project

Currently developing a ASP MVC site.
Some sections of the site will use VueJS for displaying some list, forms etc.
The project setup is Bower, Grunt, standard C# ASP project using TypeScript.
This is my first time using Vue, and the simple stuff is pretty stragt forward. Seting up a page with a form, getting data from a WebService etc.
My problem/question is, what, and how, do i get the best setup, for using Single File Components (Vue) in my cshtml view files.
So, lets say I have a section on my site, where i want to display orders from the user.
Layout, navigation etc is setup by my excisting ASP code. I have a CSHTML viewpage for the current page, pretty vanilla:
#inherits MyViewPage<MyViewModel>
#{
Layout = "~/Views/layout.cshtml";
}
<div id"app">
</div>
Thats it for the excisting view page. In this page, i want to include a Vue Single File Component.
Previously i had the markup directly in the CSHTML page, which works fine. But when i want to user Vue-router, it becomes a problem to maintain the different views. So i should move the markup into a Component.
This is the basic setup;
const page1 = { template: '<div>Page1</div>' }
const page2 = { template: '<div>Page2</div>' }
const routes = [
{ path: '/', component: page1 },
{ path: '/page2', component: page2 }
]
const router = new VueRouter({
routes
})
var vm = new Vue({
router,
el: "#app"
})
Lets say i create a .vue file called page1.vue instead. This contains
<template>
my new page
</template>
<script>
export default {
name: '?',
date: function() {
}
}
</script>
How do i get this file included in my CSHTML file for instance?
You need to develop with webpack to build Single File Components.
See the Vue documentation on this.
Use the Vue Cli and drop a web pack build into your cshtml page.

How to set asp.net mvc routing for deployment in windows azure?

I am working on Asp.net mvc 4. I am trying to deploy my project on windows azure as a webrole. I have made caustom routes in global.asax(i.e. RouteConfig.cs) file like,
routes.MapRoute(
name: "DefaultConn",
url: "{id1}/{id2}",
defaults: new { controller = "mycontrollername", action = "actionname", id = UrlParameter.Optional }
);
It actually works in local environment. But when i publish my website into windows azure environment it shows 404 Page Not Found Page.
I have accessed the page with the following url,
http://xxx.cloudapp.net/mmdg/kli
It gives 404 page not found exception. so please guide me.

Adding extra url parameter causes jquery error

Intro
I'm developing a project with MVC.Net. I have just started a default website with a Home Controller and an Index action. I browse to the view with 'Home/Index/1' and everyting works fine.
Now I want to add an extra url parameter, so I've changed my global.asax and added a foo parameter:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}/{foo}", // URL with parameters
new {controller = "Home", action = "Index", id = UrlParameter.Optional, foo = UrlParameter.Optional} // Parameter defaults
);
On the page I also have a little bit of jquery. For example this script:
<script type="text/javascript">
$(document).ready(
function ()
{
});
</script>
Problem
But now when I browse to my page with 'Home/Index/1/1' I get a javascript error:
Microsoft JScript runtime error: Object expected
When I browse to the page with 'Home/Index/1' everything works fine. Probably there's a problem with my url routing, but I have no clue what I'm doing wrong.
You can also use the following syntax to force the resolution of the path
<script src="<%: Url.Content("~/Scripts/jquery-1.4.1.js") %>" type="text/javascript">
The cause of the problem is your Script source location. I assume your script source is ../../Scripts/jquery.js which this is always being created by the application when you attach a js file in your page.
Explained.
js file mapped in `../../Scripts/jquery.js`
Page is `Home/Index/1/1`
js real content is placed in `/Scripts`
when the parser looks for the js it looks in `/Home/Scripts`
which is not where it where it is. Since ../.. = /Home in Home/Index/1/1
My Suggestion is
<%
string baseUrl = "http://" + Request.Url.Host + (Request.Url.Port != 80 ? ":" + Request.Url.Port.ToString() : "");
$>
<script type="text/javascript" language="javascript" src="<%=baseUrl %>/Scripts/jquery-1.4.1.js"></script>
This also goes to your CSS files included in your page. But for CSS links you don't put " in your href attribute of the <link> tag
Related to my answer in here

Can .net mvc routing cause JavaScript errors?

I am having a lot of trouble using routing infrastructure of asp.net mvc2. I have following routes registered in my global.asax file
routes.MapRoute(
"strict",
"{controller}.mvc/{docid}/{action}/{id}",
new { action = "Index", id = "", docid = "" },
new { docid = #"\d+"}
);
routes.MapRoute(
"default",
"{controller}.mvc/{action}/{id}",
new { action = "Index", id = "" },
new { docConstraint = new DocumentConstraint() }
);
The problem is with first route ("strict"). Three kind of urls can match first route. mycontroller/23/myaction, mycontroller/23/myaction/12 or mycontroller/23/mvaction/stringid. If I try to use this route without specifying value of id everything works fine for example:
Html.ActionLink("Link text", "ActionName", new{docid = 23});
Everything goes well, but if I use links like:
Html.ActionLink("Link text", "ActionName", new{docid = 23, id = 223})
This will produce url currentcontroller.mvc/23/ActionName/223 that is absolutely correct but when it loads the page it gives a JavaScript error in jquery1.4.2.min.js file.
This is strange: if I change id to someid =223 it will reflect in query string and there will be no JS error.
Edit: I have done some further debugging and found when both id and docid are mentioned in route values one thing is ignored in global.asax that is the ignore path.
routes.RouteExistingFiles = false;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.ignoreRoute is totally bypassed and I can see names of JS files in route value dictionary while debugging in my controller.
it gives javascript error in
jquery1.4.2.min.js file
The most likely cause for this is that something you are displaying on the page is different and you are performing an action that is causing the error. Can you supply enough of a sample from the rendered page to show what you are using jQuery for?
If we drag scripts from solution explorer to site.master it results in following output
<script type="text/javscript" src="../../scripts/jquery.min.js"></script>
The leading dots (..) are creating the problem. Putting source path in url.content or using /scripts instead of ../../scripts will solve the problem because these leading periods are forcing them to match some route in global.asax.

Resources