I'm trying to create custom urls for my LoadUser controller. I want the url to be
site.com/LoadUser/1.
The LoadUserByID route is above my default route. I keep getting the default error page
"Error. An error occurred while processing your request."
Can someone please point me in the right direction?
My code is as follows:
RouteConfig.cs
routes.MapRoute(
name: "LoadUserByID",
url: "LoadUser/{id}",
defaults: new { controller = "LoadUser", action = "ID", id = UrlParameter.Optional }
);
LoadUserController.cs
//
// GET: /LoadUser/[userid]
public ActionResult ID(int id)
{
ViewBag.Message = "ID page";
return View();
}
UPDATE
Code is fine and I'm new to MVC. I did not have a View created for LoadUser. I thought I could use the default view. Make sure to have a view created that correlates to your Controller/Action.
Related
By default, MVC 4 in Visual Studio 2017 sets _Layout.cshtml as the default layout for all pages. I believe it's doing this in App_Start/RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
(Index is set as the home page)
I'm still not sure how Index is getting _Layout.cshtml. But what if I'm trying to set a different view - a login page - as the home page, like this?
Also I'm trying to get rid of the Reports, Accounts, Settings, and Logout <li>'s in the header so that the page matches the design above. I'll also need a container with a form inside of it.
I've tried creating a _Login view inside of /Home and /Shared and changed "Index" to "Login" in App_Start/RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
But that's giving me an error:
How can I create a view and set that view as the default view for this MVC 4 Web App? Thanks
What you see in the defaults parameters as action is the name of the controller's method, not view, so you should create a method named Login in the Home controller and create the associated View for that (In the Login method right click and choose Add View). Then it will act as the default home page.
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
So your Home controller looks like this:
public class HomeController : Controller
{
public IActionResult Login()
{
return View();
}
//other codes
}
Also if you do not want the default layout to be used in the Login page you may add this at top of the Login page
#{
Layout = "";
}
The error you see doesn't seem to be because of the layout page.
This error is because the Login Action is missing in the Home controller.
You see, The defaults specified are Controlller="Home", Action="Login".
i.e. The compiler looks for the Login action in the Home controller. and when it doesn't find, it throws this error!
you could get rid of it by adding the login action like:
public ActionResult Login(string Uname, string Password)
{
return View();
}
in the home controller! That's for the error in the question.
Here is the solution for your problem.
You could add a different layout for each of your views by adding a razor code like below, to specify the layout for the view.
#{
Layout = "~/Views/Shared/_Layout.cshtml";
//This is the path to the layout. You could change this to your custom layout's path.
}
Hope this helps!
I have the following in my RouteConfig.cs file
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Home Controller has the following:
[Route("NewIncident")]
public ActionResult NewIncident()
{
var viewModel = new IncidentFormViewModel();
viewModel.NextPage = 2;
return View("NewIncident",viewModel);
}
[Route("EditIncident/{id?}")]
public ActionResult EditIncident(int? id)
{
return View("EditIncidentPage" + id);
}
[Route("SaveIncident")]
public ActionResult SaveIncident(IncidentFormViewModel incidentviewmodel)
{
return RedirectToAction("EditIncident/" + incidentviewmodel.NextPage);
}
From my index view, I can click a button that has the #Html.ActionLink as follows:
#Html.ActionLink("New Incident", "NewIncident", "Home", null, new { #class = "btn btn-primary" })
I access the site at http://sitename/ and it loads my index page. I can click the New Incident button and it loads http://sitename/NewIncident just fine, but when I click the Save button on the New Incident form, it calls the SaveIncident function just fine, but when it hits the return RedirectToAction("EditIncident/" + incidentviewmodel.NextPage); it sends me to http://sitename/Home/EditIncident/2 instead of just http://sitename/EditIncident/2.
Any idea why its adding the /Home in there?
The parts of the URL are http://sitename/Controller/Action/Parameter.
Your EditIncident ActionResult lives inside your Home Controller, and so you will therefore always see Homein front of EditIncident.
When you redirect to another Action, you can specify which controller to look for the ActionResult in with RedirectToAction("ActionName", "ControllerName"). If no Controller is specified, it assumes you want to use the same controller that you are currently in.
yes, Tot Zam are ok, and you need to create an action result method on your controller, this should be bind with a view
Found the issue.
Apparently I need to use Redirect(), not RedirectToAction() for my purposes.
Once I changed this, it rendered the correct URL without adding /Home to it
I'm creating an MVC project and I have the following link that leads to a list of websites for the logged in user:
http://[server]/Members/Websites
now I would like to add a new custom route under the websites part of the user that will lead to a service connection page:
http://[server]/Members/Websites/Connect-to-service/999
where "999" is the id of the website that is being connected.
I've defined the following route for that manned (placing it above the default route):
routes.MapRoute(
name: "myRoute",
url: "Members/Websites/Connect-to-service/{id}",
defaults: new { controller = "Members", action = "Connect_To_Service" }
);
now, if I enter the url "http://[server]/Members/Websites/Connect-to-service/999" it loads my page fine.
if I enter the url "http://[server]/Members/Websites/Connect-to-service/" it loads the websites page.
what I would like to have is when loading "http://[server]/Members/Websites/Connect-to-service/" it will either redirect to "http://[server]/Members/Websites/" (in the browser url), or throw a page not found error.
can this be done?
thanks
You could configure this in the Connect_To_Service action:
public ActionResult Connect_To_Service(int? id = null)
{
if (!id.HasValue)
{
// Either:
return RedirectToAction("Websites", "Members");
// Or:
return HttpNotFound();
}
// An id is provided. Process..
}
You might need to change your route by adding a default value for id:
defaults: new { controller = "Members", action = "Connect_To_Service", id = UrlParameter.Optional }
I have two very simple routes
routes.MapRoute(
"post", // Route name
postPage + "/{slug}", // URL with parameters
new { controller = "Home", action = "Article" } // Parameter defaults
);
routes.MapRoute(
"page", // Route name
"{slug}", // URL with parameters
new { controller = "Home", action = "Page", slug = homePage} // Parameter defaults
);
And here is my controller logic
public ActionResult Article(string slug)
{
return View(repo.GetPost(slug));
}
public ActionResult Page(string slug)
{
if (slug.ToLower() == MetaData.PostsPage.ToLower())
return View("listPosts", repo.GetAllPosts());
else
return View("page", repo.GetPage(slug));
}
homePage and postPage are set from value's in the database. Allowing the user to define the default page as well as the page to show posts.
My issue occurs when adding an area named "Admin". I get a controller added to my RouteTable
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
Now when a user Access Admin/Account/Logon the page loads fine, but my debugger still tries to go into the Home controller and the Page action. But the RouteDebugger says it doesn't match the current request. I'm puzzled on how to fix this.
RouteDebugger screenshot: http://i.stack.imgur.com/7cpHm.png
Debugger going into my HomeControler Page AtionResult: http://i.stack.imgur.com/uSJBK.png
Actually the problem is, Area routes are overriding the global routes, to distinguish both the routes set the relevant namespace of area's controller in the context.MapRoute method in adminAreaRegistraton.cs file. i.e.
context.MapRoute(
"admin_default",
"admin/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
null,
new string[] { "MVCApplication1.Areas.admin.Controllers" }
);
I found out the issue.
I had a favicon.ico set in the main area of my site, but not the Admin area.
So when I went to the Admin area the browser made a request for favicon.ico that got picked up by that route. Thats why my routes looked fine in the RouteDebugger, because they were.
Thanks for the help Kundan!
trying to map the following style of route: http://site.com/username in the same way that you can do http://www.twitter.com/user
My initial solution was to have these routes:
//site.com/rathboma - maps to user details for rathboma
routes.MapRoute("Users", "{id}", new { controller = "Users", action = "Details" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "oneday" } // Parameter defaults
);
And that was working fine, until I tried to do the following in my 'Links' controller:
public ActionResult Details(string id)
{
int newId;
if (!int.TryParse(id, out newId))
return RedirectToAction("Index");
WebLink results = Service.GetWebLink(newId, 5);
if (results == null)
return RedirectToAction("Index");
return View(results);
}
These RedirectToAction methods try and return the browser to http://site.com/Users (I do have a users controller) instead of directing to http://site.com/Links/index
Why is this is happening?
How should I be organizing my routes to make this work properly?
I'm happy sacrificing http://site.com/links and moving to http://site.com/links/index if I have to. But how would I enforce that?
Thanks to all for any help
EDIT:
I know what's causing this, it's trying to redirect to http://site.com/links (the index page), but links is being picked up as a username and redirecting to /users/details, when it can't find the user 'links' it tries to redirect to the UsersController Index action which maps to /users, and the cycle continues ('users' is not a user it can find so redirects infinately).
So I guess My sub-question is: how to I make mvc always use /links/index instead of just using /links for the index page?
Try adding this route before your Users route:
routes.MapRoute("Links",
"{controller}/{id}",
new { controller = "Links", action = "Details" });
This should then work for
http://mysite.com/Links/id
&
http://mysite.com/username
I believe changing RedirectToAction("Index"); to RedirectToAction("Index", "Links"); in your Links controller should solve the issue without having to change your routes.
The problem is you have two very greedy routes. What I'd do is to break apart the default route to less greedy routes like this :
routes.MapRoute("Links",
"Links/{id}",
new { controller = "Links", action = "Index" });
routes.MapRoute("Users",
"{id}",
new { controller = "Users", action = "Details" });
routes.MapRoute("Default",
"",
new { controller = "Home", action = "Index" });
Causing the urls to be like the following :
site.com/links/5 - hits the Links controller
site.com/name - hits the Users controller
site.com/ - hits the home controller