Issue with views using Areas - asp.net-mvc

I am about to pull my hair out!!
So I have areas setup in my MVC 3 project, I have an AccountController and Model as well as a view
When you add an area VS sets up the structure for you and I have not modified that. With all of that said, my views are not working. The controller works, when I set a breakpoint I see
// **************************************
// URL: /Account/LogOn
// **************************************
public ActionResult LogOn()
{
return View();
}
It is getting hit however I get the YPOD(Yellow page of Death) when returning the view. I have tried a view with partial rendering as well as the LogOn.cshtml, partial being located in the shared folder for the area and the non partial in the Views/Account folder.
Is this just broken or am I missing something?

I was missing a controller="Account" in my area registration. It now works:
public class AccountAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Account";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Account_default",
"Account/{controller}/{action}/{id}",
new { area = "Account", controller = "Account", action = "Index", id = UrlParameter.Optional }
);
}
}

Related

ASP.NET MVC - Attribute Routing not finding area view

I've been searching for answers for this everywhere, but I can't seem to find any. I basically have an MVC application setup and I am using the built in AttributeRouting for my routes.
The folder structure looks like this;
Models
Views
Controllers
Areas
Member
MemberAreaRegistration.cs
Controllers
HomeController.cs
Views
Home
Account.cshtml
And then I wire up my routes in the global.asax like this;
public class Application : System.Web.HttpApplication {
protected void Application_Start(){
AreaRegistration.RegisterAllAreas();
// other web optimization stuff
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
So then, MemberAreaRegistration.cs is simple.
namespace App.Web.Areas.Member {
public class MemberAreaRegistration: AreaRegistration {
public override string AreaName { get { return "Member"; } }
}
public override void RegisterArea( AreaRegistrationContext context){ }
}
And I try to wire it using the attributes...
/areas/member/controllers/homecontroller.cs
// ...
[Route("member/account")]
public ActionResult Account() { return View(); }
// ...
The problem is that this finds the route, but it cannot find the view. I get the following error;
The view 'Account' or its master was not found or no view engine
supports the searched locations. The following locations were
searched:
~/Views/Home/Account.aspx
~/Views/Home/Account.ascx
~/Views/Shared/Account.aspx
~/Views/Shared/Account.ascx
~/Views/Home/Account.cshtml
~/Views/Home/Account.vbhtml
~/Views/Shared/Account.cshtml
~/Views/Shared/Account.vbhtml
By all accounts, this should work fine - and if not, I expect the ~/area to at least be in the path it is trying to search. Do I have to wire something additional up to make this function?
I am using ASP.NET MVC 5.0
If I hardcode the absolute path of the view, it works. Obviously this is not a good situation though. I'd prefer it to find the view out of convention. But if I type return View("~/areas/member/views/home/account.cshtml"); I do get the view back - so I know it can access to file and that it is correct.
Here is my RouteConfig.cs per request
RouteConfig.cs
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
// mvc attribute routing allows us to supersede normal routing mechanisms and
// declare our routes a bit more verbosely
routes.MapMvcAttributeRoutes();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "App.Web.Controllers" }
);
}
}
That's because, once you are defining your route as an action's attribute, ASP.NET MVC doesn't know which area it is in, hence it doesn't know where to look for Views.
In the Controller the Account action is in, try to explicitly specify a RouteArea attribute.
I'm writing this off the top of my head, but it should look like:
[RouteArea("Member")]
[RoutePrefix("member")]
public class HomeController: Controller {
[Route("account")]
public ActionResult Account() { return View(); }
}
or, alternatively:
[RouteArea("Member")]
public class HomeController: Controller {
[Route("member/account")]
public ActionResult Account() { return View(); }
}

Blank screen in rendering Page Areas after update from Asp.net MVC 4 to MVC 5

I have a Facebook Application as an Area inside my Web Site. It has been developed using the Microsoft.Mvc.Facebook namespace and following the Facebook Template shipped with Visual Studio 2012.
Everything worked fine until i upgraded my project to ASP.NET MVC 5.
Now, whenever i open the app from Facebook, i got a white screen. No exception. No application_error. anything. I can even debug the code step by step down to the view and the layout, it looks everything fine, but...it doesn't render anything.
Some info could help. This is my AreaRegistration:
public class FacebookAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Facebook";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "Facebook_default",
url: "Facebook/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MvcPoli.Areas.Facebook.Controllers" }
);
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("Facebook")
{
// Register a DisplayMode of "Facebook" for views that are rendered from this area
ContextCondition = c => c.Request.Url.Segments.Length >= 2 && c.Request.Url.Segments[1].TrimEnd('/').Equals("facebook", StringComparison.OrdinalIgnoreCase)
});
}
}
All the controllers have been created inside the area by simply inheriting from the relative controller in the main site. For Example:
public class ActionController : MvcPoli.Controllers.ActionController
{
}
The only exception is the HomeController that has different signatures due to facebook routines (i removed the business code here):
public class HomeController : MvcPoli.Controllers.PoliBaseController
{
//
// GET: /Facebook/Home/
[FacebookAuthorize("email", "user_hometown", "user_location")]
public async Task<ActionResult> Index(FacebookContext context)
{
}
public ActionResult Permissions(FacebookRedirectContext context)
{
if (ModelState.IsValid)
{
return View(context);
}
return View("Error");
}
}
But, as said, everything worked fine before upgrade.
Can you help me please?!?
After one month of struggling, we found the solution! ASP.NET MVC 5 automatically added the X-Frame-Options attribute denying framing:
After update to MVC 5, iframe no longer works
Hope this can help someone else!

Why my controller asking for full path instead of direct return statement without parameter in mv3?

In a controller I added some logic, right clicked on that controller and added one partial view. Why return View() not going to return my added view. I checked that right clicking on the controller when click on go to view -> showing that view. But by using code return view() not returning my view. Its asking full path of the view.
return View("/Areas/Admin/Views/Search/ShowResult.ascx"); -->working
return View(); -->not working
I need to eliminate full path. Please tell me why my view not returning using this return View().
EDIT :
<%: Html.ActionLink("search", "index", new { Area = "admin", Controller = "search" }, new { style = "text-decoration: none" })%>
AdminAreaRegistration.cs
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName {
get {
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context) {
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { area = "admin",action = "index", id = UrlParameter.Optional }
);
}
}
Global.ascx.cs
public static void RegisterRoutes(RouteCollection routes)
{
AreaRegistration.RegisterAllAreas();
}
Controller :
[HttpPost]
public ActionResult ShowResult(FormCollection collection)
{
return View("/Areas/Admin/Views/Search/ShowResult.ascx"); //working properly
return View();//not working any one tell me ...
}
return View();---------------not working asking full path.please tell me
Thanks
Shouldn't the name of the ActionMethod and view name be identical for you to use return View()? Your ActionMethod name is ShowResult() and the view is named "Test.aspx". The view engine is unable to make that link therefore it asks for a fully qualified name to use return view you have to change the method name to Test or the view name to ShowResult.

MVC 3 - New Area - 404 error - Resource not found - have tried route debugger

I have a small MVC 3 app - bit of a demo ground.
I have one area and thats been working fine.
I have just added another area expecting to just spin up the app and it work - but no, 404 - The resource cannot be found.
The map route in the AreaRegistration is the default (as is the first area i created).
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Postcard_default",
"Postcard/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
I have tried adding in a specific controller into this, but nothing.
So I downloaded Phil Haack's RouteDebugger and my route is found when typing in http://server/Postcard/Create (which is where I am trying to get too)
Structure of the Area
My controller
public class CreateController : Controller
{
private ILogger Logger { get; set; }
private ICardSender Emailer { get; set; }
private IOCCardRepository CardRepository { get; set; }
public CreateController(ILogger logger, ICardSender cardSender, IOCCardRepository repository)
{
this.Logger = logger;
this.Emailer = cardSender;
this.CardRepository = repository;
}
//
// GET: /Postcard/Create/
public ActionResult Index()
{
var model = new OCPostcardModel().Create();
return View(model);
}
NOW: I have since deleted the entire area, tried again it didn't work. So I added in the specific controller in the route (Inside AreaRegistration file)
context.MapRoute(
"Postcard_default",
"Postcard/{controller}/{action}/{id}",
new { controller = "Create", action = "Index", id = UrlParameter.Optional }
);
And its working...I don't know why it didn't work when I did this before, but it is now.
Still curious though as I've not seen anyone add in this controller into route in any of the demo's i've looked at - and I haven't got it in my other area?
I ran into this when I moved a controller into an Area but forgot to update the namespace. The controller name is scoped to the Area's namespace. So "Some" in "Area" will map to App.Areas.Area.Controllers.SomeController, which didn't exist.
You were missing the controller part in your maproute
Try to add a class PostCardAreaRegistration under PostCard Area
using System.Web.Mvc;
namespace Areas.PostCard
{
public class PostCardAreaRegistration: AreaRegistration
{
public override string AreaName
{
get
{
return "PostCard";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"PostCard_default",
"PostCard/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
}

Simple MVC routing problem

I have few pages that quite similar to the others but one of them doesn't work.
When I write 'http://localhost:2265/Segment/' I get annoying error message "Server Error in '/' Application.
The resource cannot be found."
Other pages like 'http://localhost:2265/User/' works very well AND also 'http://localhost:2265/Segment/Create'. So Index of the Segment is the problem. I have used ASP.NET Routing Debugger and on other pages I get correct mappings, but I get this same error message "resource cannot be found" also when using debugger.. I think this indicates that Default route doesn't catch it either..
Any ideas?
Here is my MapRoute commands.
routes.MapRoute(
"Maintenance",
"Maintenance/{action}",
new { controller = "Maintenance", action = "Index", id = "" }
);
routes.MapRoute(
"User",
"User/{action}",
new { controller = "User", action = "Index", id = "" }
);
routes.MapRoute(
"Segment",
"Segment/{action}",
new { controller = "Segment", action = "Index", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Update:
Thank you for the quick reply!
I removed all routes except the default. It didn't solve the problem, but now the route list is shorter.
I have other classes inside my controller file like this:
public class SegmentFormViewModel
{
}
public class SegmentController : Controller
{
}
public class SegmentFormCreateModel : Segment
{
}
I tried to move it inside controller, but that didn't help either.
Is there any way to debug this problem?
Update:
Here is my controller (without contents of the methods)
public class SegmentController : Controller
{
//
// GET: /Segment/
public ActionResult Index()
{
}
//
// GET: /Segment/Details/5
public ActionResult Details(Guid id)
{
}
//
// GET: /Segment/Create
public ActionResult Create()
{
}
//
// POST: /Segment/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
}
//
// GET: /Segment/Edit/5
public ActionResult Edit(int id)
{
}
//
// POST: /Segment/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
}
}
To match your /Segment/ route you will need a "SegmentController" controller class to have an "Index" action that accepts GET requests, ie not restricted with [AcceptVerbs(HttpVerbs.Post)].
As Darin has already commented, the default route would handle all the other routes you have added so you don't need the extra routes.
After update:
Your problem is probably more to do with the actions in the Segment controller. It doesn't matter what classes you have in which file. What actions do you have in the Segment controller?
After 2nd update:
Your actions look ok so I suspect the problem is in code you have not listed.
Next steps:
1. Use the router debugger already mentioned.
2. Download the MVC source so you can step through it.
Last resort: Start a brand new project and only add the Segment controller. Then keep adding related code until you find the problem.
Use Phil Haack's RouteDebugger. It'll tell you what was matched, which often clears the problem up pretty quickly.
It's really easy to set up: drop RouteDebug.dll in your /bin folder and make this change to your App Start event:
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
}

Resources