URL path is being repeated ASP.NET - c#

I am in https://localhost:44311/ and I have those 2 buttons
When I press the Customers button I want to go to https://localhost:44311/Customers and see a list of the current Customers. Similarly https://localhost:44311/Movies and see a list of movies.
For those two I have two Controllers, named MoviesController and CustomersController.
This is my code in CustomersController:
namespace MovieLab.Controllers
{
public class CustomersController : Controller
{
public ActionResult AllCustomers()
{
var customers = new List<Customer>
{
new Customer(){ Name = "Customer 1"},
new Customer(){ Name = "Customer 2" }
};
var customerViewModel = new CustomerViewModel()
{
Customers = customers
};
return View(customerViewModel);
}
}
when I build the code above, my URL looks like this https://localhost:44311/Customers/AllCustomers
shouldn't it be https://localhost:44311/AllCustomers? (I named it AllCustomers so the URL doesn't look like Customers/Customers)

Your Default route in RouteConfig.cs looks like this:
url: "{controller}/{action}/{id}"
This will generate a url like:
https://localhost:44311/Customers/AllCustomers
Now to generate your required url, you need to set the route as (add it before the default one):
routes.MapRoute(
name: "MyRoute",
url: "allcustomers",
defaults: new { controller= "Customers", action = "AllCustomers", id = UrlParameter.Optional }
);
// default route
routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );

Related

C# Custom Map Routes / View Paths / Link Generation

Issue/Try 1:
I have a custom route map:
routes.MapRoute(
name: "User Profile",
url: "User/{userId}/{controller}/{action}/{id}",
defaults: new { Areas = "User", controller = "Kpi", action = "Index", id = UrlParameter.Optional }
);
If i manually navigate to the URL /User/f339e768-fe92-4322-93ca-083c3d89328c/Kpi/View/1 the page loads with a View Error: The view 'View' or its master was not found or no view engine supports the searched locations.
Issue/Try 2:
Stopped using the custom route and set up my controller as instead:
[RouteArea("User")]
[RoutePrefix("{userId}/Kpi")]
public class KpiController : BaseUserController
{
[Route("View/{id}")]
public async Task<ActionResult> View(string userId, int? id = null)
{
[...]
}
}
This now works i can navigate to the URL and the View displays fine.
Issue for both:
Although I can navigate manually to both and they load I can't seem to generate the URL correctly using ActionLink:
#Html.ActionLink(kpi.GetFormattedId(), "View", "Kpi", new { Area = "User", userId = Model.Id, id = kpi.Id }, null)
It generates: /User/Kpi/View/1?userId=f339e768-fe92-4322-93ca-083c3d89328c instead of /User/f339e768-fe92-4322-93ca-083c3d89328c/Kpi/View/1
URL Mapping
After some time i have found the solution for the custom mapping i was adding in the main RouteConfig.cs and not in the Area Registration. Moving the MapRoute to the Area works correctly and without the RouteArea, RoutePrefix and Route attributes in the Controller.
Area Registration
public class UserAreaRegistration : AreaRegistration
{
public override string AreaName => "User";
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "User",
url: "User/{userId}/{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
context.MapRoute(
"User_default",
"User/{controller}/{action}/{id}",
new {action = "Index", id = UrlParameter.Optional}
);
}
}
Links
Instead of using ActionLink i am now using RouteLink.
#Html.RouteLink("KPIs", "User", new { Controller = "Kpi", Action = "Index", userId = Model.Id })

mvc routing to incorrect url on http post

The default url of the application is
http://servername/Root/ITProjects
There is a menu item with 'Team' on the default page which should redirect to another controller with index which will display a dropdownlist at the following url
http://servername/Root/ITProjects/Team
It's working fine so far.
However when the user selects an item in the dropdownlist, it should go to the url below
http://servername/Root/ITProjects/Team/Index?Id=7
But it's directing to
http://servername/Team/Index?Id=7
and throwing the 404 error. It is missing the folder path 'Root/ITProjects' after the servername. It's working fine on localhost where there is no folder path but failing on deployment to test or prod servers
[AuthorizeAD(Groups = "APP_xxxx_Users")]
public class TeamController : Controller
{
public int pageSize = 5;
private IProjectService _projectService;
public TeamController(IProjectService projectService)
{
this._projectService = projectService;
}
public ActionResult Index(int? Id, int? page)
{
int pageNumber = (page ?? 1);
var viewModel = new TeamViewModel();
if (Id != null)
{
viewModel.SelectedMember = (int)Id;
viewModel.Tasks = this._projectService.GetTasksByStaff(viewModel.SelectedMember).ToPagedList(pageNumber, pageSize);
}
return View(viewModel);
}
[HttpPost, ActionName("Index")]
public ActionResult IndexPost(int Id, int? page)
{
int pageNumber = (page ?? 1);
var viewModel = new TeamViewModel();
viewModel.SelectedMember = Id;
if (ModelState.IsValid)
{
viewModel.Tasks = this._projectService.GetTasksByStaff(viewModel.SelectedMember).ToPagedList(pageNumber, pageSize);
}
return View(viewModel);
}
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
As part of Index view when dropdownlist item is selected
#Html.DropDownListFor(m => m.SelectedMember, new SelectList(Model.StaffList, "UniqueId", "Initials", Model.SelectedMember), new { #class = "btn btn-default btn-color", onchange = #"form.action='/Team/Index?Id=' +this.value;form.submit();" })
Your MVC application is in a sub-directory of another application, so IIS considers the root of the parent application instead of the root of your MVC application.
In IIS, you need to convert the virtual directory to an Application: choose your virtual directory and "Convert to Application." If you are unable to do that, then you need to modify your routes in routes.config to take the virtual directory into account:
routes.MapRoute(
"Default", // Route name
"Root/ITProjects/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
your default route for controllers looks like this :
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
You can add /Root/ITProjects/ before the URL to change the default controller path

How to route from one controller action method to another controller action method without displaying controller name in MVC 5

I have two different MapRoutes in Route.config as follows...
routes.MapRoute(
name: "Default",
url: "{action}",
defaults: new { controller = "Index",action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "SubjectRoute",
url: "{action}",
defaults: new { controller = "Subjects", action = "Subjects" }
);
and my #HTML.ActionLink is as follows in Index action method which is in IndexController
#Html.ActionLink("SUBJECTS", "Subjects","Subjects", new { }, new { #class = "text" })
Now when I click on SUBJECTS link in Index action method, it should go to Subjects action in Subjects controller with out displaying controller name in the URL.
How can this be done?
routes.MapRoute(
name: "SubjectRoute",
url: "Subjects",
defaults: new { controller = "Subjects", action = "Subjects" }
);
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Index",action = "Index", id = UrlParameter.Optional }
);
With the above, calls to
#Html.ActionLink("SUBJECTS", "Subjects","Subjects", new { }, new { #class = "text" })
should generate
/Subjects
The default and more general route will now catch all other requests and route them to the IndexControllerwhich now acts as the site root/index.
for example assuming
public class IndexController : Controller {
public ActionResult Index() {...}
public ActionResult ContactUs() {...}
public ActionResult About() {...}
}
the available routes based on above controller are
/
/Index
/ContactUs
/About

Remove Area name and Controller name from mvc routes in MVC4

I am trying to remove area name and controller name from URL.I am able to remove area name. But if trying to remove controller name then "Page not found error" displayed. Below is the code snippet which I have used to remove the area and controller name.
public class HomeAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Home";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
//context.MapRoute(
// "Home_default",
// "Home/{controller}/{action}/{id}",
// new { action = "Index", id = UrlParameter.Optional }
//);
//context.MapRoute(
// "Home_default",
// "{controller}/{action}/{id}",
// new { action = "Index", id = UrlParameter.Optional },
// new { controller = "(Home)" }
//);
context.MapRoute(
"Home_default",
"{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new { controller = "(Home)" }
);
}
}
In the registerarea function the first two routes(commented) are working perfectly. if I use the first one the URL comes with Area/Controller/Action. If I use second one the area is not coming in URL.The URL come ups with Controller/Action.
In the third one I am trying to remove both area and Controller
Is any thing wrong in my third route. Please suggest
Have you tried this:
routes.MapRoute("default", "{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional});

Change nopcommerce default action

How to change nopcommerce default action?
I create new action in HomeController, and want to be default page.
I change:
routes.MapRoute(
"",
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "Nop.Web.Controllers" }
);
To:
routes.MapRoute(
"",
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "NewAction", id = UrlParameter.Optional },
new[] { "Nop.Web.Controllers" }
);
But nothing has changed.
When you navigate to /Home/Index, MVC parses route as follows:
Controller: Home
Action: Index
Id:
If you navigate to /Home:
Controller: Home
Action: NewAction (from route's default action)
Id:
You can make it always activate NewAction like this:
routes.MapRoute(
"",
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "NewAction", id = UrlParameter.Optional },
new[] { "Nop.Web.Controllers" }
);
You can try like this.
//your default action
public ActionResult Index()
{
return RedirectToAction("NewAction"); //Like Response.Redirect() in Asp.Net WebForm
}
//your new action
public ActionResult NewAction()
{
//some code here
return view();
}

Categories