ASP.NET RouteConfig dynamic entry off Root - c#

I have statically mapped all controllers except one ... a LookupController that I would like to operate off root.
Here are my routes:
routes.MapRoute(
name: "Root",
url: "",
defaults: new {controller = "Home", action = "Index"}
);
routes.MapRoute(
name: "Home",
url: "home/{action}/{id}");
routes.MapRoute(
name: "User",
url: "user/{action}/{id}");
routes.MapRoute(
name: "Company",
url: "company/{action}/{id}");
routes.MapRoute(
name: "Recruiter",
url: "recruiter/{action}/{id}");
routes.MapRoute(
name: "Lookup",
url: "{company}/{recruiter}",
defaults: new { controller = "Lookup", action = "Index" }
);
Everything works fine EXCEPT the last entry for Lookup.
This breaks everything, including the other routes.
Basically, I want my URLs to be:
/Home
/User
/Company
/Recruiter
/{company}/{recruiter}
Any idea how I can accomplish this?
Thank you very much in advanced!
EDIT: Adding LookupController by request:
public class LookupController : Controller
{
private RecruiterSightContext db = new RecruiterSightContext();
// GET: Lookup
public ActionResult Index(string company, string recruiter)
{
if (string.IsNullOrEmpty(company) && string.IsNullOrEmpty(recruiter))
{
TempData["errorMessage"] = "No Company or Recruiter specified in URL";
return RedirectToAction("Index", "Home");
}
// Company lookup
if (string.IsNullOrEmpty(recruiter))
{
Company foundCompany = db.Companies.FirstOrDefault(c => company.ToLower().Equals(c.Slug.ToLower()));
if (foundCompany == null)
{
return RedirectToAction("Index", "Home");
}
return RedirectToAction("Display", "Company", new {companyId = foundCompany.CompanyId});
}
Recruiter foundRecruiter = db.Recruiters.FirstOrDefault(r => r.Slug.ToLower().Equals(recruiter.ToLower()));
if (foundRecruiter == null)
{
return RedirectToAction("Index", "Home");
}
return RedirectToAction("RecruiterView", "Recruiter", new {recruiterId = foundRecruiter.RecruiterId});
}
}

If your Lookup folder exists:
try to change:
from:
routes.MapRoute(
name: "Lookup",
url: "{company}/{recruiter}",
defaults: new { controller = "Lookup", action = "Index" }
);
to:
routes.MapRoute(
name: "Lookup",
url: "company/recruiter",
defaults: new { controller = "Lookup", action = "Index" }
);
then in your Browser
Add like this:
company/recruiter
If your Lookup is different of index then i think you need to create another function that calling your Lookup like:
routes.MapRoute(
name: "Lookup",
url: "company/recruiter",
defaults: new { controller = "Lookup", action = "LookupWithParameter" }
);
then in your Controller:
public ActionResult LookupWithParameter(String Company, string recruiter)
And don't forget to create another .cshtml file to redirect the page of your Lookup which is located at your Lookup folder
Here's the scenario:
Assuming that you are currently working at your Index.cshtml page which in your Home Controller then you want to redirect into Lookup page.
Index(Home) .cshtml file:
<div id="content">
#{
if (IsPost) {
<!--this option if you don't need to change another page-->
string company = Request["Company"];
string recruiter = Request["Recruiter"];
<p>You entered: <br />
Company Name: #company <br />
Recruiter Name: #recruiter</p>
}
else
{
<form method="post" action="company/recruiter">
Company Name:<br />
<input type="text" name="Company" value="" id="idcompany" /><br />
Contact Name:<br />
<input type="text" name="Recruiter" value=""id="idrecruiter" /><br /><br />
<input type="submit" value="Submit" class="submit" />
</form>
}
}
</div>
LookupController:
public class LookupController : Controller
{
//
// GET: /Lookup/
public ActionResult MyLookup(string Company, string Recruiter)
{
// this is how to pass the value of parameter company and recruiter input from index.
//Your Action here and you can use to Debug while runnning notice that the company and the recruiter has a content from index home input
return View();
}
}
RouteConfig.cs
routes.MapRoute(
name: "Lookup",
url: "company/recruiter",
defaults: new { controller = "Lookup", action = "MyLookup" }
);
Make sure that you have a Lookup folder that contains MyLookup.cshtml

Related

Take string input on default index method in mvc5

i want to take input of username value on default mvc5 home page controller Index method. I already tried to do it like bellow [Route("{Username?}")] but it suppose to get value on url: https://localhost:44330/myusername but this url not hits the Index method. Can i do it without changing in RouteConfig.cs or how can i do it changing RouteConfig.cs even?
public class HomeController : Controller
{
[Route("{Username?}")]
public ActionResult Index(string Username)
{
return View();
}
}
RouteConfig.cs code:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
You can easily do it from RouteConfig.cs. Example codes are bellow:
routes.MapRoute(
name: "Default",
url: "{username}",
defaults: new { controller = "Home", action = "Index", username = UrlParameter.Optional },
namespaces: new[] { "ProjectNameSpace.Controllers" }
);

MVC Application Username in route upon login

Upon login I want to re route to a new page. (Example: mysite.com/Dashboard/User/Username)
I also want it to verify that user is logged in before it allows access to said URL.
I'm new to MVC and C# and appreciate your help.
My controller: What do I pass into the controller to make it work?
public class DashboardController : Controller
{
// GET: Dashboard
public ActionResult User()
{
return View();
}
}
Route.config.cs:
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 = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "UserNameRoute",
url: "{username}",
defaults: new { controller = "Dashboard", action = "User", username = "" }
);
}
}
I believe it should be something like this:
routes.MapRoute(
name: "UserNameRoute",
url: "Dashboard/User/{username}",
defaults: new { username = "" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I chose not to put the {controller} and {action} placeholders in the template as that would make it equal to the default route template. You could of course use just the action template if that is what you need:
routes.MapRoute(
name: "UserNameRoute",
url: "Dashboard/{action}/{username}",
defaults: new { action = "User", username = "" }
);
Also note I put it before the default route because it is more specific. Otherwise the default route would catch every request.
Authorization is something you can't do here however. You will need to do that by e.g. creating a custom AuthorizeAttribute subclass that checks the username matches the logged in user.

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

display url slug instead of id in mvc

I have a blogging application and users are able to create posts, I used Entity framework to create the model from the database. In Posts I have an entry for UrlSlug.
However when I check the details of a post:
Controller:
public ActionResult Details(int id = 0)
{
Post post = db.Posts.Find(id);
if (post == null)
{
return HttpNotFound();
}
return View(post);
}
It returns a url with id at the end: http://localhost:52202/Post/Details/1
I have tried returning post.UrlSlug (throws an error) aswell as changing my RouteConfig.cs file to use urlslug instead of id (which does display the urlslug, but it cant find the page because of the controller). How can I change this so urlslug is displayed instead of the Post Table Id?
RouteConfig.cs
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 }
);
}
View:
#for (int i = 0; i < Model.Count(); i += 3)
{
<div class="row">
#foreach (var item in Model.Skip(i).Take(3))
{
<div class="col-md-4 portfolio-item">
<a href="#Url.Action("Details", "Post", new { id = item.Id })">
<img class="img-responsive" src="http://placehold.it/700x400" alt="">
</a>
<h3>
#Html.DisplayFor(modelItem => item.Title)
</h3>
<p>#Html.DisplayFor(modelItem => item.ShortDescription)</p>
</div>
}
</div>
}
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, pageSize = Model.PageSize }))
Edit
An issue I noticed is on this line:
public ActionResult Details(string urlslug)
{
Post post = db.Posts.Find(urlslug); //find only finds an eitity with a given primary key, how can I change this to find the string urlslug
An action method does not dictate the URL, it only matches a request. You need to print the slug:
#Url.Action("Details", "Post", new { slug = item.Slug })
Then add to the routing to support the URL structure you want:
routes.MapRoute(
name: "PostWithSlug",
url: "Post/Details/{slug}",
defaults: new { }
And alter the action method:
public ActionResult Details(string slug)
{
}
But besides that, you do want an ID in the URL. Otherwise you can't use the same post title twice.
You can either rename your argument in your controller to match the 'slug' name. So instead of
public ActionResult Details(int id = 0)
Use
public ActionResult Details(int urlslug = 0)
Alternative is to remove id from your route config like
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
Keep in mind, what ever you argument name is in your Action, that name is used as the GET variable in your url. So if the argument is int id, then your url must be like ?id=1.
An issue I noticed on the below line:
public ActionResult Details(string urlslug)
{
Post post = db.Posts.Find(urlslug); //find only finds an eitity with a given primary key, how can I change this to find the string urlslug
You can select data with the help of urlslug by using Where instead of Find
i.e. Post post = db.Posts.Where(x=> x.urlslug == urlslug).FirstOrDefault();

Working with routes.maproute and parameters

I am have a parameter that I want to use as the default ending of a URL, but it is currently a parameter. I want it to always direct to the Home Controller & Index Action, but the "/" becomes the pageName parameter.
For example, I want
http://localhost:18792/?pageName=HomePage
To be accessible by:
http://localhost:18792/HomePage
This is my current routes.maproute:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{pageName}",
defaults: new { controller = "Home", action = "Index", pageName = "HomePage" }
);
To do this, you will have to create a route for each page. Don't modify the "Default" route. . Add a new route:
routes.MapRoute(
name: "HomePage",
url: "HomePage",
defaults: new { controller = "Home", action = "HomePage" }
);
for dynamic routes, you could use:
routes.MapRoute(
name: "PageName",
url: "{pageName}",
defaults: new { controller = "Home", action = "Index", pageName = "defaultPage" }
);
which will map to ~/defaultpage or ~/homepage with the Action "Index" in the "Home" controller:
public ActionResult Index(string pageName)
{
ViewBag.Message = pageName;
return View();
}

Categories