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
Related
I’ve been trying to develop large scale application in wordpress. Been through several plugin development best practices. And finally I’ve been reading the documentation of http://wpmvc.org/
I pretty much understood its automatic (mvc) code generation tools. Its default controller functions index() & show() works pretty well.
But, when I tried to add a custom_action(), thats where I got stuck.
class DemoController extends MvcPublicController {
public function hello(){
print_r($this->params);
die();
}
}
above function hello() is only accessible by below URL:
domain.com/demo/hello/{num}
but can’t be accessed via:
domain.com/demo/hello
Do I need to write any custom route to make this work? Or, am I doing anything wrong?
Finally, I found the solution, and it was pretty easy.
In config/routes.php,
I replaced, this:
MvcRouter::public_connect('{:controller}/{:action}/{:id:[\d]+}');
with this:
MvcRouter::public_connect('{:controller}/{:action}');
[ IMPORTANT ] Don't forget to save permalinks to flush rewrite rules.
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
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).
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.
Is it possible to add a TaskItem (or TaskList) to the website page (Web Objects Home Page)?
I'd like to provide some contextual access to my addin and I can't seem to find a good integration point.
Many thanks to CarlosAg on the IIS.net forums for the basis of this answer.
Create a class that subclasses ProtocolProvider and have it return a TaskList by overriding GetSiteTaskList and GetSitesTaskList.
In your Module.Initialize method, get an IExtensibilityManager from the serviceProvider
Register an instance of your ProtocolProvider to the IExtensibilityManager by calling RegisterExtension.
Update
It turns out a ProtocolProvider can only provide a TaskList for the "Sites" view, but can provide a different TaskList depending on which site is selected (if any).
To provide a custom TaskList for a site's homepage (ie. with the list of features), you need to implement IHomepageTaskListProvider and register it with the IExtensibilityManager mentioned above.
Within the IHomepageTaskListProvider.GetTaskList implementation, you can find out if you the current "homepage" is a site or global by getting a Connection from the IServiceProvider and checking the ConfigurationPath.PathType property (it's an ConfigurationPathType enumeration)