MVC 2.0 View that starts with a number - c#

I'm using c#, visual studio 2010. I'm new to MVC
I was supplied with a simple HTML page that I converted to an aspx view. I then added the controller.
The view directory is Views/150/Index.aspx. The issue is that when I go to add the controller, the class name is not allowed to be a number.
namespace MyPages.Controllers
{
public class _50Controller : Controller
{
public ViewResult Index()
{
return View("Index");
}
}
}
When I entered the have the controller a number, it automatically changed it from 150 to _50. So I changed it to 150Controller.cs and changed the class name to 150Controller : Controller.
Unfortunately, you can't have a number as a class name, and _50Controller as the class name tries to direct to Views/_50/Index.aspx.
I would simply change the name, however I was specifically asked to have it as a number. I know I can set up a redirect in ISS... but is there another way to do this?
Thanks!

In C# members cannot start with a number. You could use routing in order to achieve that:
For example you could have the following controller:
public class ErrorController : Controller
{
public ActionResult Index()
{
return View("500");
}
}
which could be routed like this:
routes.MapRoute(
name: "Error",
url: "500",
defaults: new { controller = "Error", action = "Index" }
);
Now when you navigate to http://example.com/500 it will be the Index action of ErrorController that will get executed and which will render the 500.aspx view.

Related

Using Route Attribute with Html.Action C# MVC

I have the following application hierarchy:
Area > Website > HomeController > HeaderAction
Once I decorated my controller action with a route attribute, the #Html.Action in my Layout View stopped working
[RouteArea("Website", AreaPrefix = "Home"), Route("{action}")]
public class HomeController : Controller
{
[Route("~/header", Name = "head")]
public ActionResult Header()
{
WebsiteModel model = new WebsiteModel();
return PartialView(model);
}
}
#Html.Action("head")
Now I have to use AreaRegistration instead
Does anyone know what my problem is?
Thanks in advance
I think your problem is that you defined your route as [Route("~/header", Name = "head")] which make the route relative to the base application path. In your code you use #Html.Action("head") which uses the name of the route you defined instead of the actual route.
Try changing it to
#Html.Action("header")

How to pass data to controller's field from URL?

I know how to send data to controller's action method as parameter from URL. Here I wonder how can I send data from URL to controller's field?
public MyAwesomeController : Controller {
public string SectionCode { get;set; }
}
and let's define Routes :
routes.MapRoute(
name : "AwesomeRouter",
url : "{code}/{action}",
defaults: new {controller = "MyAwesome", action = "Index", /* What to do here?*/}
);
I want SectionCode be filled with the {code} from URL. Is it possible to implement?
Yes it is, you can create inherited class from basic Controller class and override OnActionExecuting method where you can read url, route or any form data and store them in session or directly fill any field you need. Then create an inherited class of your controller.
public class MyAwesomeController : MyControllerBase
{
public ActionResult Index()
{
//this.SectionCode is available populated here
return View();
}
}
public class MyControllerBase : Controller
{
public string SectionCode
{
get;
private set;
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
this.SectionCode = filterContext.RequestContext.RouteData.Values["code"].ToString();
base.OnActionExecuting(filterContext);
}
}
Each time you hit any action in this controller using route definition you provided, field will be automatically populated. But when you will have more than one route defined they it could get easily into conflicts eg. when code will match to any controller name. Normal website should not work this way.
Your route should look like this:
routes.MapRoute(
name: "AwesomeRouter",
url: "{code}/{action}",
defaults: new { controller = "MyAwesome", action = "Index" }
);
The code should then be passed on to the action as a parameter. I am storing it in the view bag for explanation purposes:
public class MyAwesomeController : Controller
{
public ActionResult Index(string code)
{
ViewBag.Code = code;
return View();
}
}
Using this URL then:
http://somehost/4567/Index
If you access the Viewbag property in your view:
#ViewBag.Code
You should see:
4567

Strange behaviour with controller and view inside area MVC 5

I have one area called user.
The area configuration looks like this
context.MapRouteLowercase(name: "User_Member", url: "User/Member", defaults: new { controller = "User", action = "Member", id = UrlParameter.Optional });
When I browse to this page without passing in a id, it returns the view my url looks like this /user/member
When I type the following into the browser /user/member/1
I've put a break point on
var userId
and it gets hit and I check the id parameter and its 1 which is correct.
[HttpGet]
[Authorize]
public ActionResult Member(Int64 id = 0)
{
var userId = id != 0 ? id : ReturnUserId();
var model = _userProfileBusinessLayer.GetProfile(userId);
return View(model);
}
Yet when I press F5 I get the following page
Server Error in '/' Application.
The view 'member' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/user/member.aspx
~/Views/user/member.ascx
~/Views/Shared/member.aspx
~/Views/Shared/member.ascx
~/Views/user/member.cshtml
~/Views/user/member.vbhtml
~/Views/Shared/member.cshtml
~/Views/Shared/member.vbhtml
I'm unsure why I'm seeing that because all I have done is added /1 to the url?
I should be seeing the profile of the user which matches then id of 1, yet I remove /1 and it returns the view ?!?!?!?! slightly baffled
In your project, the area user should have a class that inherits from AreaRegistration e.g.
public class UserAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "user";
}
}
}
In that class you can define routes sepcific for that area:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"UserManagement",
"user/Admin",
new { controller = "UserAdmin", action = "Index" });
}
The file Global.asax.cs should have an Application_Start() method which calls:
AreaRegistration.RegisterAllAreas();
That will pick up the area routes you have configured. This is usually how area routes are configured. Do you have a similar setup for your project?

AreaRegistration MapRoutes for Help Docs

I have an api using web api 2 and I am trying to create help docs within an Area so that an incoming request like ...api/people.help will route to the people controller and people view and serve up the html. I am struggling with the route mapping for the area after refactoring the code. Previously, I had routes like this:
public override void RegisterArea(AreaRegistrationContext context) {
context.MapRoute(
name: "Help",
url: "{action}.help",
defaults: new { area = "help", controller = "default" }
);
All the methods were in the default controller and this worked. Now, I need a separate controller for each resource (eg people, schedules etc) but can't get the routes to work. I would appreciate help, I am very new to this. How do I get each help request to map to the controller with the same action name?
Wouldn't it simply be something similar to:
public override RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "Help",
url: "api/{controller}.help",
defaults: new { area = "help" }
);
}
What you have in your post is a default for the name of the controller, in this case, it's name will always be default. Instead, what you're looking for is that when someone routes to your controller name suffixed with .help, it'll route to a path akin to api/help/people, which will end up calling a default action (in MVC) such as index.cshtml or the default action for a GET request to the controller (for WebAPI).
So, you want to set the default area to help as shown above. You also want to set the default action that should execute on the provided controller.
Update: To answer question in comment
For MVC, you can have an action method whose name matches what the controller name will be in the URL:
public class PeopleController : Controller
{
[HttpGet] // Not strictly necessary, but just want to stress this is GET
public ActionResult People()
{
// Do stuff in your action method
}
}
The only problem is, your action method will be different for each controller, and so unknowable for route registration purposes. Therefore, you should maybe have just a default Help action:
public class PeopleController : Controller
{
[HttpGet]
public ActionResult Help()
{
// Do stuff
}
}
Then you can have the following route:
public override RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "Help",
url: "api/{controller}.help",
defaults: new { area = "help", action = "Help" }
}
You could take this one step further and provide a Help method in a custom base controller class:
public class MyBaseController : Controller
{
public virtual ActionResult Help()
{
// Do default behavior stuff, if appropriate
}
// If you don't have any "default" behavior, you could make the method abstract:
// public abstract ActionResult Help();
}
public class PeopleController : MyBaseController
{
public override ActionResult Help()
{
// Do stuff.
}
}
Update to further answer OP's question in comments
So, now the OP is saying: "but I want my view to have the same name as my controller." Ok, that should be no problem:
public class PeopleController : MyBaseController // if you're using a base class
{
public override ActionResult Help()
{
return ViewResult("People");
}
}
So, you can have a view with any name you want. But if the view's name differs from the name of the action method, then when returning (say) a ViewResult, you'll need to specify the name of the view to return.
Having said all that, the default folder structure for views in ASP.Net is Areas/{AreaName}/Views/{Controller}/{viewname}.{cs|vb}html. And here, {viewname} is by default assumed to be the action method name, but doesn't have to be when, as above, explicitly telling MVC which view to return (in the example above, People.cshtml).
HTH.

The resource cannot be found error for MVC 3

I know there are a lot other topics like this, but from what I found, and did accordingly to the answers - I still have the error.
The Global.asax:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Func", action = "Main", id = UrlParameter.Optional } // Parameter defaults
);
The Controller:
public class FuncController : Controller
{
//
// GET: /Func/
public ActionResult Main()
{
return View();
}
public ActionResult Products()
{
return View();
}
And accordingly the 2 .cshtml View files with the Main and Products names.
In the "Project Properties->Web" I selected "Start URL" with value "http:// localhost:63497/Main". I don't get it where might the problem be, as in the other topics I found about this error, the problem was always in some of these things. But now, everything seems to be fine, and still - error.
Main is the Action method. You need to navigate to the Controller and let that hit the appropriate Action. Try navigating to:
http:// localhost:63497/Func/Main
Which is Func Controller. ActionMethod Main
try like this..
http://localhost:63497/Func/Main.
because the route is from controller to ActionResult.
so, here Func is the Controller and the Main is your ActionResult Method.
so, you have to use the controller first in url before the Action Method.

Categories

Resources