Here's the controller code:
public ActionResult AddFriend(string username)
{
//Todo: Add functionality to add a friend.
//Then redirect to that same profile.
return RedirectToAction("Detail", "Profile", username);
}
Contents of username is stapia.gutierrez, not 16 or anything like that.
When I visit the link:
http://localhost:9198/profile/friend/add/stapia.gutierrez
The above action is called because I create a route in Global.asax:
routes.MapRoute("AddFriend", // Route name
"Profile/Friend/Add/{username}", // URL with parameters
new { controller = "Profile", action = "AddFriend" } // Parameter defaults
);
After clicking the URL is shown as:
http://localhost:9198/Profile/stapia.gutierrez?Length=16
Any ideas?
You need to pass the route values like so:
return RedirectToAction("Detail", "Profile", new { username="value" });
Related
I have a route as
routes.MapRoute(
"User", // Route name
"Person/{action}", // URL with parameters
new { controller = "User" } // Parameter defaults
);
that means if I put url like
http://localhost/myApp/Person/Detail
then it should invoke Detail action of User controller, right?
Ok, I have done it and routing also works good, means it invoke action properly.
Now if I want to get controller name then I will use
ControllerContext.RouteData.Values["controller"];
and that will give me User, but I want it to be Person (i.e. as in URL). How can I get that?
The Request.Url property of Controller will return a Uri object containing details of the current url, including the segments.
string[] segments = Request.Url.Segments;
// returns ["/", "Person/", "Detail"]
string value = segments[1].Remove(segments[1].Length - 1);;
// returns "Person"
you can get controller name by following code
HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
If you're in a view, then you can do:
ViewContext.RouteData.Values["Controller"]
and for custom url you can define
[Route("myApp/Person/{action?}")]
public ActionResult View(string id)
{
if (!String.IsNullOrEmpty(id))
{
return View("ViewStudent", GetStudent(id));
}
return View("AllStudents", GetStudents());
}
I am using mvc 5 to create user accounts , and I want the users to have profile paths like so example.com/username
is it possible to do it and how if yes ?
Thanks
You need to create a routing entry in your global.asax:
RouteTable.Routes.Add(new Route
{
Url = [username],
Defaults = new { Controller = "YourController", Action = "YourAction" }
});
Then your controller should look like this:
class YourControllerController : Controller
{
public ActionResult YourAction(string username)
{
...
}
}
I'm working on a simple MVC application, where I am generating below path
#Html.ActionLink(#objcity.CityName, "AgentProfiles", "Home", new {#Id=objcity.MaProvision.ProvinceName+"/"+#objcity.CityName }, null)
It makes a url like this:
http://localhost:45896/Home/AgentProfiles/Ontario/testt
In the controller I have written this method:
public ActionResult AgentProfiles(String Id)
{
//Code
}
Is it possible to get in /Ontario/testt in Id variable?
You want to get /Ontario/testt in Id(route parameter) for this you have to modify your default routes little bit or you have to make a custom route but in my opinion for your simple requirement try below answer.
Instead of
#Html.ActionLink(#objcity.CityName, "AgentProfiles", "Home", new {#Id=objcity.MaProvision.ProvinceName+"/"+#objcity.CityName }, null)
Modify Actionlink this way
#Html.ActionLink(#objcity.CityName, "AgentProfiles", "Home", new { ProvinceName=objcity.MaProvision.ProvinceName ,CityName = objcity.CityName }, null)
Controller Action :
public ActionResult AgentProfiles(string ProvinceName,string CityName ) //get ProvinceName and CityName which will be coming as querystring variables as shown here.
{......}
OR
EDIT :- Try this as per your comment.
Add one more route in RouteConfig.cs file inside AppStart folder as shown below :
routes.MapRoute(
"MvcRoutes", // Route name
"{controller}/{action}/{provincename}/{cityname}", // URL with parameters
new { controller = "Home", action = "Index", provincename = "", cityname= "" } // Parameter defaults
);
Don't forget to put this custom route above default route.
Modify ActionLink as shown below :
#Html.ActionLink(#objcity.CityName, "AgentProfiles", "Home", new { provincename = objcity.MaProvision.ProvinceName , cityname = objcity.CityName }, null)
Controller Action :
public ActionResult AgentProfiles(string provincename ,string cityname)
{......}
you can modify your routing like-
{controller}/{action}/{*catchall}
and in action method
public ActionResult AgentProfiles(string catchall)
{
// your code
}
Then you will have value /Ontario/testt in your catchall parameter which you can use in action method.
How do I redirect to a route without getting a query string on my URL?
Route configuration...
routes.MapRoute(
name: "ApplicationStatus",
url: "join/ApplicationStatus/{applicationKey}/{characterId}",
defaults: new { controller = "Join", action = "ApplicationStatus" }
);
Controller code to redirect...
return RedirectToAction("ApplicationStatus", new {
applicationKey = applicationKey,
characterId =_sm.JoinState.CharacterId
});
Controller action method...
public ActionResult ApplicationStatus(string applicationKey, long characterId)
{
return View(new ApplicationStatus());
}
So when I am redirected from the controller the browser gives me the following url...
http://localhost/TestApp/Join/ApplicationStatus?applicationKey=xxxxxxx&characterId=nnnnnnnn
but I would like to get this...
http://localhost/TestApp/Join/ApplicationStatus/xxxxxxx/nnnnnnnn
Thanks in advance.
You should use RedirectToRoute.
Try this instead.
return RedirectToRoute("ApplicationStatus", new {
applicationKey = applicationKey,
characterId =_sm.JoinState.CharacterId
});
My goal is to have the url routing as following:
http://www.abc.com/this-is-peter-page
http://www.abc.com/this-is-john-page
What is the simplest way to achieve this without placing controller name an function name in the url above? If page above not found, I should redirect to 404 page.
Addon 1: this-is-peter-page and this-is-john-page is not static content, but is from database.
Similar to KingNestor's implementation, you can also do the followings which will ease your work:
1) Write Your Model
public class MyUser{public String UserName{get; set;}}
2) add route to global asax
routes.MapRoute(
"NameRouting",
"{name}",
new { controller = "PersonalPage", action = "Index", username="name" });
3) Roll your own custom model binder derived from IModelBinder
public class CustomBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
var username = getUserNameFromDashedString(request["username"]);
MyUser user = new MyUser(username);
return user;
}
}
4) in your action:
public ActionResult Index([ModelBinder(typeof(CustomBinder))] MyUser usr)
{
ViewData["Welcome"] = "Viewing " + usr.Username;
return View();
}
I personally wouldn't suggest a route like that but if it meets your needs you need to do something like:
Have the following route in your Global.asax file:
routes.MapRoute(
"NameRouting",
"{name}",
new { controller = "PersonalPage", action = "routeByName" });
Then, in your "PersonalPageController", have the following method:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult routeByName(string name)
{
switch (name)
{
case "this-is-peter-page": return View("PeterView");
case "this-is-john-page": return View("JohnView");
case Default: return View("NotFound");
}
}
Make sure you have the appropriate views: "PeterView", "JohnView" and "NotFound" in your Views/PersonalPage/.
I don't think this can be done. AFAIK ASP.NET MVC recognizes routing parameters via the character "/".
Your format, on the other hand, goes by "{controller}-is-{id}-{action}" -- so there is no way the controller can be distinguished from the id and the action.
I think using "/" characters doesn't affect or degrade SEO; it only affects human readability and retention of the URL.
Anyway, the following URL is possible: http://www.abc.com/this-is-the-page-of/Peter by adding another route in the Global.asax RegisterRoutes method:
routes.MapRoute(
"AnotherRoute",
"this-is-the-page-of/{id}",
new { controller = "PersonalPage", action = "Details", id = "" }
);
...assuming that PersonalPageController implements a Details ActionResult method that points to the desired page.