开发者

MVC3 Controller folder won't appear in URL

This is just an example which I can't figure out how to get it work.

In my MVC3 Controller folder, if I add a new folder called "Admin" and add a controller "News" with an action "Index", you get a server error when you try to open that url (404):

http://url/Admin/News

开发者_开发知识库Even when you type "/Index" behind it, it won't work. How can you make a hierarchy which will result in similar URL's? Just to be clear, I want to create URL's like:

http://url/folder1/folder2/controller/action

Thanks


You seem to be thinking in the mindset of "physical file paths" still. .NET MVC uses the concept of routing where you define routes that map to controller classes and actions. In plain words, you're not mapping to a file, you're mapping to a class.

If you look in the global.asax file of your web project you will see a method named RegisterRoutes(). This method wires up all of the available routes for your site that will be utilized to find the correct controller/action/param/pattern to execute.

Now, the way I'd recommend solving what you're looking for would be by creating an area. It sounds like you want to have an administrative section to your website so I'd do the following:

Right click on your website project, select "Add", select "Area"

MVC3 Controller folder won't appear in URL

Give your area a name, in this case "Admin" would make sense

You solution explorer will now have added the "area" Admin. Notice how it mimics the structure and layout of the standard project, only in it's own folder.

MVC3 Controller folder won't appear in URL

Add a controller in the newly created administrative area and name it "News" Add your actions

Here's a test result URL doing this:

MVC3 Controller folder won't appear in URL

This solution is for simplicity's sake. If you want to take if further you will have to delve into creating your own routes in the RegisterRoutes() method I spoke of above. Routing is something you should gain a solid grasp of so I recommend doing so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜