HTTP 404 Server Error in '/' Application. in ASP.NET MVC 4 - c#

`First, this is my first MVC code & I tried to search for the solution to the problem in this site & I checked all the possible cases like routeconfig file, controller,action properties & I tried to put appropriate values in specified page of Web Tab of Project Property. But still it showing the same error. Some help please.
here my routeconfig file
namespace Deepak_MVC_2
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Student", action = "GetStudents", id = UrlParameter.Optional }
);
}
}
}
specific page entry : Student/GetStudents
namespace Deepak_MVC_2.Controllers
{
public class StudentController : Controller
{
public ActionResult GetAllStudent()
{
StudentModelManager smm = new StudentModelManager();
List<StudentModel> lsm = smm.GetAllStudentInfo();
ActionResult ar = View("GetStudents",lsm);
return ar;
}
}
}

Update your controller's action to match the View you want. with that You can actually remove the name when returning the view as convention will match the ViewName to the action name.
namespace Deepak_MVC_2.Controllers
{
public class StudentController : Controller
{
public ActionResult GetStudents()
{
StudentModelManager smm = new StudentModelManager();
List<StudentModel> lsm = smm.GetAllStudentInfo();
ActionResult ar = View(lsm);
return ar;
}
}
}
this will allow
GET /Student/GetStudents
to be matched to the correct view as in your image

Related

Special MVC Routing not working

I'm having problems with the routings in my MVC project not working...
I want all my views in the Views > Shared folder like this:
Error.cshtml (default)
Index.cshtml (default)
Overview.cshtml (custom that I made)
Recordings.cshtml (custom that I made)
I've then created one shared controller to handle all views like this:
public class SharedController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Error()
{
return View();
}
public ActionResult Overview()
{
return View();
}
public ActionResult Recordings()
{
return View();
}
}
My RouteConfig.cs looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Map to specific pages under Shared controller:
routes.MapRoute("SharedPages", "{action}/{id}",
new { controller = "Shared", action = #"Overview|Recordings", id = UrlParameter.Optional });
// Use the default rout for all other pages:
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Shared", action = "Index", id = UrlParameter.Optional }
);
// Show the Error page for anything else (404):
routes.MapRoute("Error", "{*url}",
new { controller = "Shared", action = "Error" }
);
}
I want the routing to work like this:
://(url)/ (root - no action specified) --> Shared/Index.cshtml
://(url)/Index --> Shared/Index.cshtml
://(url)/Overview --> Shared/Overview.cshtml
://(url)/Recordings --> Shared/Recordings.cshtml
://(url)/whatever (or if an error occurs) --> Shared/Error.cshtml
But it's not working as expected. If I go to ://(url)/ (root), I get a HTTP 404 - The resource cannot be found. If I go to for example ://(url)/Overview, it's working fine.
How can I make it work like I want?
The order of how you map route is important and first matched route wins. That means that even if there is no resource there one it matches the route it will use it.
public static void RegisterRoutes(RouteCollection routes)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Use specific rout for all other pages:
routes.MapRoute("WhateverA", "WhateverA/{action}/{id}",
new { controller = "WhateverA", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute("WhateverB", "WhateverB/{action}/{id}",
new { controller = "WhateverB", action = "Index", id = UrlParameter.Optional }
);
// Map to specific pages under Shared controller:
routes.MapRoute("RootPages", "{action}/{id}",
new { controller = "Shared", action = "Index", id = UrlParameter.Optional });
// Show the Error page for anything else (404):
routes.MapRoute("Error", "{*url}",
new { controller = "Shared", action = "Error" }
);
}
The problem with the Default and SharedPages routes is that they conflict with each other. You may need to provide specific routes for other controllers if they exist. Other wise the other option is to use Attribute Routing for the other controllers and convention-based routing for your root routes and error
public static void RegisterRoutes(RouteCollection routes)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Attribute routing
routes.MapMvcAttributeRoutes();
// Map to specific pages under Shared controller:
routes.MapRoute("RootPages", "{action}/{id}",
new { controller = "Shared", action = "Index", id = UrlParameter.Optional });
// Show the Error page for anything else (404):
routes.MapRoute("Error", "{*url}",
new { controller = "Shared", action = "Error" }
);
}
With controllers decorated accordingly
[RoutePrefix("WhatEver")]
public class WhatEverController : Controller {
//GET whatever
[HttpGet]
[Route("")]
public ActionResult Index() { ... }
}

URL Routing with an MVC

I am making a website that displays a bunch of articles. It is built off a MVC I want to be able to search for articles by day and then by an ID number via url.
If the domain name is website.com, I'm trying to figure out how to make routes so that website.com/yyyymmdd hits a specific controller+method and displays all the articles for that day and website.com/yyyymmdd/111 searches that day's articles for article #111.
The issue I'm having is that all the tutorials for routing within an MVC assume I will specify the controller and method in the URL. They show something like:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" });
}
If anybody could suggest a way to automatically make "website.com/yyyymmdd/111" use a specified controller and method, that'd be amazing. Thanks in advance!
EDIT:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Today",
"{date}/{id}",
new { controller = "Articles", action = "Index", date = DateTime.Today.ToString("yyyyMMdd"), id = UrlParameter.Optional });
}
I've done this as my route and my method is as follows:
public ActionResult ArticlesByDate(string date, int id)
{
if(id > 1)
{
return View(Contact());
}
else
{
return View(About());
}
}
I hope I am understanding your guys' suggestions, but this is giving me a "Resource can not be found" error when i try to navigate to: "http://localhost:52159/20160908/2"
One way this can be solved by using the date as a parameter to the action.
Your action would look like
public ActionResult Index(string articleDate,string id) ...
The your route definition would be something like
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default",
"{controller}/{action}/{articleDate}/{id}",
new { controller = "Home", action = "Index",articleDate=DateTime.Today.ToString("yyyyMMdd"), id = "" });
}
Then you can take it from there
Second route for default mvc routing mechanism.
First route is for articles.Controller and action value is static. You can change date and id values for website.com/20160911/111 , website.com/20160912/112 etc.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
name: "Articles",
url: "{date}/{id}",
defaults: new { controller = "Articles", action = "Info"});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
public class ArticleController : Controller {
public ActionResult Info(string date, int id){
return View();
}
}
you cant redirect two view in an action. Use one view and partial views within.
for example
Info.cshtml
#if(id > 1)
{
#Html.Partial("_Contact")
}
else
{
#Html.Partial("_About")
}

Routing doesn't find controller with the same name as area

I followed article about Areas in ASP:NET MVC 4 (section How to Avoid Name Conflict). I'm using MVC 5, but I suppose all the features from version 4 are available and should work in version 5.
My directory structure:
File EpicAreaRegistration.cs content:
namespace App1.Web.UI.Areas.Epic
{
public class EpicAreaRegistration : AreaRegistration
{
public override string AreaName
{
get{ return "Epic"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRouteLocalized(
name: "Epic_default",
url: "Epic/{controller}/{action}/{id}",
defaults: new { controller = "Pm", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "App1.Web.UI.Areas.Epic.Controllers" }
);
}
}
}
My project's App_Start -> RouteConfig.cs file content: UPDATE corrected namespace
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "App1.Web.UI.Controllers" } // according to article namespace must be added here, so ASP.NET router distinguishes between request: e
);
}
}
And finally I have EpicController.cs file in project's directory Controllers:
namespace App1.Web.UI.Controllers
{
public class EpicController : Controller
{
public ActionResult Browse()
{
return View();
}
}
}
When I navigate to: http://localhost:7300/Epic/Pm it works (finds it), but http://localhost:7300/Epic/Browse doesn't work (404 - not found). What have I missed?
My assumption is that request goes through some kind of routing table. If it doesn't find Epic/Browse in Areas, it should move to project's root Controller folder. It's the same analogy as with Views (folder, if not in folder look in Shared, ...)
Additionally I registered all areas in Application_Start
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
....
Make sure your Area controller uses the correct namespace.
Namespace for EpicController is currently:
namespace App1.Web.UI.Controllers
Change it to:
namespace App1.Web.UI.Areas.Epic.Controllers
Your controller is also Epic. So your URL would look like
http://localhost:7300/Epic/Epic/Browse
This may help you to access,
http://localhost:7300/Areas/Epic/Epic/Browse
As It's contained in sub folder.

ASP.Net view folder with a folder inside - How to create the controller

I want to create a URL similar to: localhost:port/farm/animals/cow.cshtml.
How do I create a controller for pages behind /animals/ ?
If I create a standard:
public class FarmController : Controller
{
//
// GET: /Farm/
public ActionResult Cow()
{
return View();
}
}
I will not get there because the cow.cshtml is behind the animals.
Nor will I get to cow.cshtml with the following code:
public class AnimalsController : Controller
{
//
// GET: /Animals/
public ActionResult Cow()
{
return View();
}
}
Because the link to cow.cshtml is not /animals/ but /farm/animals/cow.
How can I solve this issue?
You need to register a route like the following -
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Animals",
url: "farm/animals/{action}",
defaults: new { controller = "Farm" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Controller
public class FarmController : Controller
{
// GET: Farm
public ActionResult Index()
{
return View();
}
// GET: Farm/Animals
public ActionResult Animals()
{
return View();
}
// GET: Farm/Animals/Cow
public ActionResult Cow()
{
return View();
}
}
Whilst routing would solve your problem, this sounds like a job for MVC areas. If in your actual application you're wanting to separate parts of your site, then an area might be the solution here.

How to set up specific routing in mvc3 web application

I have problem with routing. I have many pages on my site generated dynamically from database.
First thing which I want to accomplish is to route to these pages like that:
"How to repair a car"
www.EXAMPLE.com/How-to-repair-a-car
For now it works like that: www.EXAMPLE.com/Home/Index/How-to-repair-a-car
Secondly my default page have to be like that: www.EXAMPLE.com
On the Start Page will be news with pagging, so if someone click for instance in the "page 2" button, the address should looks: www.EXAMPLE.com/page =2
CONCLUSION:
default page -> www.EXAMPLE.com (with page = 0)
default page with specific page of news -> www.EXAMPLE.com/page=12
article page -> www.EXAMPLE.com/How-to-repair-car (without parameter 'page') routing sholud point to article or error404
PS: sorry for my english
Try to create route for articles in routing config, like this:
Routing config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(null, "{article}",
new {controller = "Home", action = "Article" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
HomeController:
public class HomeController : Controller
{
public ActionResult Index(int? page)
{
var definedPage = page ?? 0;
ViewBag.page = "your page is " + definedPage;
return View();
}
public ActionResult Article(string article)
{
ViewBag.article = article;
return View();
}
}
/?page=10 - works
/How-to-repair-car - works
That approach excellent works.
Here is a basic routing example for www.example.com/How-to-repair-car
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Tipser.Web
{
public class MyMvcApplication : HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"ArticleRoute",
"{articleName}",
new { Controller = "Home", Action = "Index", articleName = UrlParameter.Optional },
new { userFriendlyURL = new ArticleConstraint() }
);
}
public class ArticleConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var articleName = values["articleName"] as string;
//determine if there is a valid article
if (there_is_there_any_article_matching(articleName))
return true;
return false;
}
}
}
}

Categories

Resources