Building a simple site using ASP.Net MVC 3 - asp.net

I'm using mvc3 to build a simple site with 5 static pages. I'm just wondering what the best practice is in this situation. So far I have only one 'Page' Controller which has 5 functions, each returning the appropriate view.
I've also updated the global.asax file to use:
routes.MapRouteLowercase(
"Default", // Route name
"{action}/{id}", // URL with parameters
new { controller = "Page", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
I realise that the general rule is use one controller for each logical unit so I figure this works out okay for a small site?
Is this a suitable approach or should I do it differently?
Thanks.

Your approach is fine.
However, if you have just static pages, why do you use MVC at all? You can just deploy a bunch of .html files and be done with it.

Related

Conventional controller organisation

I just started to work with ASP.NET MVC, and I am quite lost about the use of controllers for static pages.
I won't have many pages, all of them will be static pages, except contact page I guess but I would like to get them well organised like :
Home page :
http://www.mywebsite.com/home/
Company pages :
http://www.mywebsite.com/company/about/
http://www.mywebsite.com/company/contact/
Then some legal pages :
http://www.mywebsite.com/legal/privacy-policy/
http://www.mywebsite.com/legal/cookie-statement/
Does it mean that I have to create 3 controllers ? HomeController, CompanyController and LegalController ? Or is managed from the routes ?
And are the Index actions mandatory ?
Thank you for your help.
As it sounds like a simple site, I wouldn't over complicate things with multiple controllers. Instead just keep with the default controller and decorate the actions instead.
For example:
[HttpGet("/Company/About")]
public IActionResult About()
{
return View();
}
However if the site gets more complex then you may want to add controllers depending on the project. You'll then also probably have to revisit your routing strategy as a whole.
For more information on routing, see here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-3.1#routing-basics
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1#attribute-routing

ASP.NET Routing Interference Problems

I'm having a mind shattering problem with ASP .NET routing. I can't tell if this is a bug in Microsoft code or if I'm just using it wrong.
The scenario is basically this:
I have a custom route I want to add. In addition, I'm registering ASP .NET DynamicDataRoutes. If I leave out my custom route, all the ASP .NET DynamicDataRoutes work fine. Once I add this before my DynamicDataRoute:
routes.Add(new Route("IgnoreDirectory/{*pathInfo}"), new StopRoutingHandler()));
all the DynamicHyperlinks generated by DynamicData are generated with the wrong root url, like this one:
http://localhost/IgnoreDirectory/MyTable/List
which should be (and was until I added my custom route)
http://localhost/MyDynamicData/MyTable/List
What's weird is that I'm adding my DynamicDataRoute for a COMPLETELY different path:
routes.Add(new DynamicDataRoute("MyDynamicData/{{table}}/{{action}}")
{
Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
Model = model
});
Why is adding a route for IgnoreDirectory causing my DynamicData routes to use a base url of IgnoreDirectory????
I can't figure it out.
I'm going out on a limb here, but I think it has to do with two things. The order that the routes are stored in the RouteTable are significant in that the application will use the first route it finds in order to match the URL.
What I think might be happening here is that the DynamicDataRoute is building itself upon the Route that you are inserting before the DynamicDataRoute in the route table.
The first thing I would do is try moving the Route add after the DynamicDataRoute has been added.
Hope this helps...

ASP.NET MVC 3, IIS7, 404 Error, not routing correctly?

I'm newish to ASP.NET MVC 3, so sorry if I'm my details are slightly murky. I'm trying to publish my web app to a server here. I'm running in IIS 7, set to integrated, and I can get to the home page of the app just fine. However, certain links remove the directory out of the url. Example:
URL of home page:
http://localhost/CMS/ - this will take you to the first screen, with links to "Contract," "Customer," and "Employee." Clicking one of those brings you to...
http://localhost/CMS/Contract (or whichever you choose.) From there, it's broken down into different categories. One of them is "Create Contract." Here's the problem I'm having: that URL points to
http://localhost/Contract/Create - completely omitting the CMS part out and throwing a 404. I can reach it by inserting CMS back inside, and those pages route correctly.
What could be wrong? Let me know if you need more information on any of my code or whatever.
You can define an alternate controller in the route than what you would expect
routes.MapRoute("Contract", "Contract/{action}",
new { controller = "cms", action = "index" }
);
and you should be constructing your links like this within your pages
<%=Html.ActionLink("Contract", "create", "cms") %>
rather than doing it the old fashioned way like
Contracts
which side steps routing.
It sounds like you don't need additional routes but need to create ActionLinks propery using the HtmlHelper
When you are using your paths to to the controller actions you need to use #Url.Action("action", "controller"); instead of just using "action\controller".
See an example http://codetuner.blogspot.com/2011/07/jquery-post-url-problems-in-iis-hosted.html

Design and implementation for Short URLs on IIS and ASP.NET stack

I'm interested in creating "short URLs" a segment of pages on a site. However, this isn't in the traditional sense of "short URLs" like bit.ly where it will redirect to a different destination URL. I want the short URL to be the final destination.
For example, one of these URLs might be http://foo/a/Afjbg, and when you navigate to it, it stays on http://foo/a/Afjbg (IOW, http://foo/a/Afjbg is visible to the user in the address bar).
If it was static content, I would just arrange the pages and folders into these names. But the content I will have on the site will be dynamically driven from a DB, so each page is generated on the fly. So the content looks logically different, but in reality is essentially the same .aspx page with dynamic content.
How can this be accomplished on a Microsoft hosting stack? The platform is IIS 7 with ASP.NET 4. I figure there is a way to easily set this up, but being new to the MS hosting stack, I have no idea :)
Use ASP.NET MVC routing
It allows routing of any URL pattern to a "page"
e.g.
routes.MapRoute(
"Default", // Route name
"a/{id*}", // Route anything to this controller
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
It's called URL routing, and ASP.NET supports it natively since version 3.5. Here is an example in C#, taken from MSDN. The squiggly brackets individuate chunks of the URL path that get sent as parameters to ~/categoriespage.aspx.
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("",
"Category/{action}/{categoryName}",
"~/categoriespage.aspx");
}
You could use most any .NET-based CMS or blog engine and just make the slug a short string.
Details:
In most CMS and blogging engines, the software separates the slug from post title. It will auto-generate one for you if you don't specify a slug... for example, a post titled "Hello world" might get a generated slug of "hello_world". But you can type in your own slug to be "Afjbg".
Or if you want to get a little more sophisticated, both of the programs I cited above are open-source - which means you can easily modify the slug generation component to auto-generate these little strings.
You could try to use ASP.NET routing, but without knowing more about the application you're using or building, that might not work out easily (i.e. some CMS engines might already use routing, or use old-school handlers that don't play nicely with it).

asp.net mvc how to manage urls/links and routing centrally (c# + js)

I keep running into problems with URLs and routing.
Couldn't find an answer on SO.
I would like to manage all of my urls/links in a single place.
This is for my C# MVC code and the js/jquery ajax code.
These urls are scattered throughout my application.
Moving to a production server needs some fixes and I don't like the fact that I need to look for all of the occurrences in the application.
I don't mind fixing this once - but I would like to do it only once.
Any ideas how to manage all of these links/urls as a group will be very appreciated.
Be happy ad enjoy life, Julian
Consider using T4MVC
You could use Html.ActionLink or
Html.BuildUrlFromExpression(c => c.ControllerAction())
Depends, if you have application reading off certain urls and those urls changed once in a while. then you might want to consider putting all those urls into a database table/etc and retrieve them using specific key.
that way, when your url changed, all you need to do is to change the url on your database and all your application will still be running fine.
Urls should be managed in a single place: the RegisterRoutes static method in Global.asax. In absolutely every other part of your application you should use Html helpers when dealing/generating urls. This way you will never have problems because helpers take into account your routing system.
So instead of writing:
$('#foo').click(function() {
$('#result').load('/mycontroller/myaction');
return false;
});
you use an HTML helper to generate this foo:
<%: Html.Action("foo", "myaction", "mycontroller") %>
and then:
$('#foo').click(function() {
$('#result').load(this.href);
return false;
});
Never hardcode a single url in your application except of course in global.asax which is the only centralized place urls should be defined. So basically every time you find yourself writing something of the form /foo/bar in some other part than global.asax you are doing it wrong.

Resources