I am following this tutorial to create the first mvc application (Create a Movie Database Application).
I already added the create view, but when I click on the Create new link, the page does not exist. Typical 404 error.
I tried
/home/create
/create
/create.aspx
/home/create.aspx
I am very newbie at MVC, so please dont laugh. :)
EDIT: GLobal .asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Movies.Models;
namespace Movies.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
private LearningEntities _db = new LearningEntities();
public ActionResult Index()
{
return View(_db.Movies1.ToList());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")] Movie movieToCreate)
{
if (!ModelState.IsValid)
return View();
_db.AddToMovies1(movieToCreate);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
}
You need a Get as well as Post Create method in your controller. You need the following
public ActionResult Create()
{
return View();
}
public ActionResult Create([Bind(Exclude = "Id")] Movie movieToCreate)
{
....
}
Edit: The URL to your create view is /Home/Create
You dont have a create "get" action.
Basically the create action you have there is for when a form is submitted.
You need this code from the tutorial:
// GET: /Home/Create
public ActionResult Create()
{
return View();
}
The Create you have is for HttpPost which you'll use when you are trying to create an entity. Initially you'll need to have a controller method with HttpGet create method which will let you enter data for a new entity. Also, make sure your view is in Views->home folder.
Related
I just want to customize routes in asp.net mvc ,
This is a blog website and I want to access controller methods using
wwww.sitename.com/blog/{blogtitle}
www.sitename.com/blog/{action}
Blog Controller
public class BlogController : Controller
{
public ActionResult Index(string title)
{
return View();
}
[Route("post-blog")]
[HttpPost]
public ActionResult Post(Blog blog,HttpPostedFileBase blogimage)
{
//some coe
}
[Route("post-blog")]
public ActionResult Post()
{
if (Request.Cookies["userInfo"]==null)
{
return Redirect("/login");
}
return View();
}
}
Here is route Config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.Canonicalize().Www();
routes.Canonicalize().Lowercase();
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "freelogomaker", id = UrlParameter.Optional }
);
}
But I am unable to hit action name "Index" using www.site.com/blog/titlename
But I can access "post-blog" using www.site.com/blog/post-blog
Please help me I am beginner in asp.net mvc routing.
Add your parameter to the route attribute within {} brackets to indicate that it should be read from the URL, and not from something else (such as POST body, dependency injections, etc)
[Route("{title}")]
public ActionResult Index(string title)
{
return View();
}
I also like to add the RoutePrefix attribute to the controller to make it a bit clearer.
[RoutePrefix("blog")]
public class BlogController : Controller
i am currently trying to generate this url "/Cloud/Hosting/RoaringPenguin/Manage/Exclusions".
Here is the area registration
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Hosting_default",
"Cloud/Hosting/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
here is the controller
public class RoaringPenguinController : PortalControllerBase
{
public ActionResult Exclusions()
{
return View("Exclusions");
}
}
i have tried added a route onto the action itself like so
[Route("Manage/Exclusions")]
public ActionResult Exclusions()
I have also tried adding some attributes to the controller itself
[RouteArea("Hosting")]
[RoutePrefix("RoaringPenguin")]
public class RoaringPenguinController : PortalControllerBase
but that doesn't seem to work either. If i leave all the attributes off then the final url i get is "/Cloud/Hosting/RoaringPenguin/Exclusions".
Does anyone know how i can get the "Manage" in the url as well?
Just to confirm i have the following set in my RegisterRoutes method under the RouteConfig class
routes.MapMvcAttributeRoutes();
Any help is appreciated. Thanks
Your default area route doesn't allow for the "Manage/Exclusions" part on the end. If you made the URL just /Cloud/Hosting/RoaringPenguin/Exclusions (minus the Manage part of the path) it would work fine.
If you need the route to be exactly that, then attribute routing is your best bet. However, your mentioned attempts at that are all missing something or another. Your controller should be decorated with both RouteArea and RoutePrefix to compose the first part of the path:
[RouteArea("Hosting", AreaPrefix = "Cloud/Hosting")]
[RoutePrefix("RoaringPenguin")]
public class RoaringPenguinController : Controller
However, it's typical to actually implement a base controller when dealing with areas, so that you can specify RouteArea in just one place:
[RouteArea("Hosting", AreaPrefix = "Cloud/Hosting")]
public class HostingBaseController : Controller
[RoutePrefix("RoaringPenguin")]
public class RoaringPenguinController : HostingBaseController
Then, on your action:
[Route("Manage/Exclusions")]
public ActionResult Exclusions()
As you had.
Try with this code
[RouteArea("AreaName", AreaPrefix = "Cloud/Hosting")]
[RoutePrefix("RoaringPenguin")]
public class SampleController : Controller
{
[Route("Manage/Exclusions")]
public ActionResult Exclusions()
{
return View("Exclusions");
}
}
or
[RoutePrefix("Cloud/Hosting/RoaringPenguin")]
public class RoaringPenguinController : PortalControllerBase
{
[Route("Manage/Exclusions")]
public ActionResult Exclusions()
{
return View("Exclusions");
}
}
This will be the first line
routes.MapMvcAttributeRoutes();
After that only you have to write this line
AreaRegistration.RegistrationAllAreas();
I am working on a new project and i have decided to use attribute routing alone. This is my RouteConfig file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}",
// defaults: new { controller = "HomeController", action = "Index", id = UrlParameter.Optional }
//);
}
This is my controller:
[RoutePrefix("home")]
public class HomeController : Controller
{
[Route]
[Route("~/")]
public ActionResult Index()
{
var status = HttpContext.User.Identity.IsAuthenticated;
ViewBag.Title = "Home Page";
return View();
}
[Route("test")]
public ActionResult Test()
{
return View();
}
}
I've realised that typically all my attributes are working but i want the Index method to run on application start. Say https://example.com and then the Index method is fired as if i entered the url https://example.com/home/index. I get a blank space when i do say https://example.com.
Can anyone please help me understand why i get a blank space and also how to set the default application start route using attribute routing? I've been surfing the internet for hours but i can't lay my hands on anything.
In your case you should still set a default route. That way the site knows where to start. From there everything else should work as you intended.
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{action}",
defaults: new { controller = "Home", action = "Index" }
);
}
Here is my Home Controller.
public class HomeController : FrontOfficeControllerBase {
public HomeController() {
}
public ActionResult Index() {
...
return View();
}
}
Other than that this keeps my route config clean as I use attribute routing everywhere else.
Try this:
[RoutePrefix("home")]
public class HomeController : Controller
{
[Route("index")]
[Route("~/", Name = "default")]
public ActionResult Index()
{
...
}
...
}
I'm trying to understand how the route config works in the MVC 5.
I have the following structure for my application:
BaseCRUDController
public class BaseCRUDController<TEntity, TEntityViewModel> : Controller
where TEntity : class
where TEntityViewModel : class
{
private readonly IBaseService<TEntity> baseService;
public BaseCRUDController(IBaseService<TEntity> service)
{
this.baseService = service;
}
[HttpGet]
public virtual ActionResult Index()
{
IList<TEntityViewModel> entities = baseService.FindFirst(10).To<IList<TEntityViewModel>>();
return View(entities);
}
}
CountriesController
[RouteArea("management")]
[RoutePrefix("countries")]
public class CountriesController : BaseCRUDController<Country, CountryViewModel>
{
private readonly ICountryService service;
public CountriesController(ICountryService service)
: base(service)
{
this.service = service;
}
}
What I'm trying to do is simple: http://myapplication.com/management/countries.
I have many others controllers that the superclass is the base controller. I'm doing this way to avoid code repetition, since that the controllers have similar structure.
The problems are:
I can't reach the url that I want (/management/countries)
I don't know how to configure my Home Controller, because I want that it could be reached by http://myapplication.com
How could I fix these problems?
My route config is like that:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
After a little playing around I managed to get it to work.
The problem is when you are using attribute routing there are no default route parameters assigned.
For example in your Default route the defaults are controller = "Home", action = "Index". So if you were to call http://myapplication.com/ the routing engine will automatically default to /Home/Index/ and so on.
However the attribute route has no way of knowing you want to default to the Index action (or any other action for that matter).
To solve the issue add the Route attribute to the CountriesController like this:
[RouteArea("management")]
[RoutePrefix("countries")]
[Route("{action=Index}")] // this defines the default action as Index
public class CountriesController : BaseCRUDController<Country, CountryViewModel>
{
private readonly ICountryService service;
public CountriesController(ICountryService service)
: base(service)
{
this.service = service;
}
}
Also for future reference Phil Haack's Route Debugger is extremely helpful for figuring out routing issues.
Have you defined Area (management) for your controllers?
if you try without Area, is that getting redirect properly?
I'm working on an MVC application and I have and admin area... So what I need is:
When user makes request to admin (for example "/Admin/Post/Add") I need to map this to controller AdminPost and action Add... is it possible?
If your controller is named AdminPostController and you want it to map to '/Admin/Post/Add' then you can use:
routes.MapRoute("Admin", // Route name
"Admin/Post/{action}/{id}", // URL with parameters
new { controller = "AdminPost", action = "Add", id = "" } // Parameter defaults
);
Note the use of the parameter defaults.
If your controller is named AdminController and you just wanted to separate the request method then use the default:
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Which will map '/Admin/Add/' to the controller:
public class AdminController : Controller {
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(int id) {
//...
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Add(int id) {
//...
}
}
Note the use of [AcceptVerbs] to identify which method to invoke for POST requests and GET requests.
See Scott Gu's blog for more details