Problem with giving id to action - c#

I configured routes in Global.asax.cs like this:
routes.MapRoute("Post", "Post/Show/{PostId}", new { controller = "Post", action = "Show" });
and this is preview of used controller with action:
public partial class PostController : Controller
{
public ActionResult Show(int PostId)
{
...
}
}
The problem is that it selects Show() action to use but it gives no int value,therefor it gives null.Here is an example of URL I used:../Post/Show/0
EDIT:
When I configure my routes like this :
routes.MapRoute("Post", "Post/Show/{id}", new { controller = "Post", action = "Show" });
routes.MapRoute("Timeline", "{controller}/{action}/{Page}", new { controller = "Timeline", action = "List" });
everything works fine,but when I configure it like this:
routes.MapRoute("Timeline", "{controller}/{action}/{Page}", new { controller = "Timeline", action = "List" });
routes.MapRoute("Post", "Post/Show/{id}", new { controller = "Post", action = "Show" });
2nd route "Post" fails.
Why ?!

You should try:
routes.MapRoute("Post", "Post/Show/{PostId}", new { controller = "Post", action = "Show", PostId = UrlParameter.Optional });

This should work just remember the order the routes appear in global.asax is very important too.
routes.MapRoute(
"Post", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Post", action = "Show", id = UrlParameter.Optional } // Parameter defaults
)

Related

ASP.NET MVC C# Multiple Url Routes Config Controller Action

I want create route config multiple Url. ex: "fr-ca/user/login" and "en-ca/user/login" and its working, but if click submit and proccess data by controller and return RedirectToAction(MVC.User.Dashboard); always return "fr-ca/user/dashboard";
Although I use Url "en-ca/", and always return all link MVC.anything in first is "fr-ca/"
Because in position route config, "fr-ca" is first.
Maybe somebody can help me to solve this, thank u.
routes.MapRoute(
name: "fr-Default",
url: "fr-ca/{controller}/{action}/{id}",
defaults: new { controller = MVC.Content.Name, action = MVC.Content.ActionNames.Show, id = UrlParameter.Optional, siteId = Site.FR.Id },
namespaces: new string[] { "Jay.Cms.Web.Controllers" }
);
routes.MapRoute(
name: "en-Default",
url: "en-ca/{controller}/{action}/{id}",
defaults: new { controller = MVC.Content.Name, action = MVC.Content.ActionNames.Show, id = UrlParameter.Optional, siteId = Site.EN.Id },
namespaces: new string[] { "Jay.Cms.Web.Controllers" }
);
You can write to action attribute in controller
'[Route("fr-ca/{controller}/{action}/{id}")]
[Route("en-ca/{controller}/{action}/{id}")]
public ActionResult Home()
{
return View();
}'

ASP.NET Core: How to connect route parameter with query

I have route with connected action which retrieves blog post drom database and displays it.
routes.MapRoute(
name: "GetPostToShow",
template: "posts/{postId:int}",
defaults: new { controller = "Home", action = "GetPostToShow" },
constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });
Which results in url
https://localhost:44300/posts/2002
But I want it to look like this
https://localhost:44300/posts?postId=2002
So how I can implement it?
?postId=2002 is a GET variable and can be gotten as an argument in the controller method.
So you wouild simplify your MapRoute:
routes.MapRoute(
name: "GetPostToShow",
template: "posts",
defaults: new { controller = "Home", action = "GetPostToShow" },
constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });
And in the Controller have the Method:
public IActionResult GetPostToShow(int postId)
Of course even nicer is to use the decorator routing in my opinion. Then you would remove the MapRoute call and instead add the following decorator to the method:
[HttpGet("posts")]
public IActionResult GetPostToShow(int postId)
Your routes look like below
routes.MapRoute(
name: "GetPostToShow",
template: "posts/{postId(0)}",
defaults: new { controller = "Home", action = "GetPostToShow" },
constraints: new { httpMethod = new HttpMethodRouteConstraint(new string[] { "GET" }) });
Your GetPostToShow method in controller side look like below.
public virtual IActionResult GetPostToShow (int postId)
{
// your code and return view
}
Or into CSHTML page you want to use like below code.
#Url.RouteUrl("posts", new {postId= yourpostsIdhere})

HttpVerbs.Get and parameters?

I have the following action :
public class IntegrationController : Controller
{
[AcceptVerbs(HttpVerbs.Get)]
public ContentResult Feed(string feedKey)
{
...
}
}
I have tried to use this URL :
http://MyServer/Integration/Feed/MyTest
but feedKey is null? Does this have something to do with routes?
Edit 1 :
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Ad", action = "List", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"TreeEditing", // Route name
"{controller}/{action}/{name}/{id}", // URL with parameters
new { controller = "AdCategory", action = "Add", name = string.Empty, id = -1 }
);
Edit 2 :
routes.MapRoute(
"IntegrationFeed", // Route name
"{controller}/{action}/{name}/{feedKey}", // URL with parameters
new { controller = "Integration", action = "Feed", name = string.Empty, feedKey = "" }
);
Do you have a route defined for feedKey? Using the default routes, the following should work (change feedKey to id).
[AcceptVerbs(HttpVerbs.Get)]
public ContentResult Feed(string id)
{
// ...
}

How can I add a route in controller

I'd like to map a new route after I commit a new object to db. So for example if i enter object with name "Test" I would like to have a new route immediately, to resolve "Test.aspx".
I tried
System.Web.Routing.RouteTable.Routes.MapRoute(obj.NameUrl, obj.NameUrl + extension, new { controller = "per", action = "Index", name = obj.NameUrl });
in controller but it does not work (no error, just probably not right time in life cycle?). Same code works in Application_Start()
You should avoid registering routes dynamically. The following static route in your Application_Start should be able to handle your scenario of having dynamic route parameters:
routes.MapRoute(
"page",
"{name}.aspx",
new { controller = "per", action = "index" },
new { name = #"[a-z0-9]+" }
);
and if the extension has to be dynamic as well:
routes.MapRoute(
"page",
"{name}.{extension}",
new { controller = "per", action = "index" },
new { name = #"[a-z0-9]+", extension = #"[a-z]{3,4}" }
);
and then you could have the Index action to handle requests to this route:
public class PerController: Controller
{
public ActionResult Index(string name, string extension)
{
...
}
}
and if you want to generate a link to this action:
#Html.RouteLink("go to foo", "page", new { name = "foo", extension = "aspx" })

how to write a route which include the username

I am building an asp.net mvc website, after the user login he can access his profile section pages and currently these pages URL is like that www.example.com/profile , what I want is to make the URL like that www.example.com/USERNAME
How to write this route which will work just in profile page when the user login?
Update:
based on the answers below, I wrote it like this:
routes.MapRoute(
"AccountSettins",
"AccountSettings",
new { controller = "AccountSettings", action = "Index" }
);
routes.MapRoute(
"myRouteName",
"{username}",
new { controller = "Profile", action = "Index" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
and the controller:
[Authorize]
public class ProfileController : BaseController
{
//
// GET: /Profile/
public ActionResult Index(string username= "")
{ ...
But now after the user login and his user name was "xyz" he can go to www.example.com/xyz and this will lead to the profile page, but if he also wrote the url www.example.com/abc he will go to the same profile page normally which is something strange from the user point of view, how to solve this issue?
In your Global.asax...
routes.MapRouteWithName(
"routeUserProfile",
"{username}",
new { controller = "User", action = "Profile", username = "" });
In your User controller....
public ActionResult Profile(string username) {
//conditional logic to check if username is user
// render user profile with special user-only stuff
//else
// render only generic stuff about user
}
routes.MapRoute(
"myRouteName",
"{username}",
new { controller = "Home", action = "Profile" }
);
You can specify you controller and action you want and just use the username for your parameter for the method Profile of the Home class.
You will need to write a controller specifically for this and create a route like:
routes.MapRoute(
"UserPage", // Route name
"{username}", // URL with parameters
new { controller = "User", action = "Index", username = ""} // Parameter defaults
);
See here for more details:
http://dotnet.dzone.com/articles/aspnet-mvc-routing-basics?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Fdotnet+(.NET+Zone)
In the global.asax file add the following routes
routes.MapRoute(
"UsersRoute", // Route name
"{username}", // URL with parameters
new { controller = "Test", action = "Index", username = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
And according to the first route add the following controller as bellow
public class TestController : Controller
{
public ActionResult Index(string username )
{
var p = username;
return View();
}
}
To prevent user to see others profile, just check in the action if he/she can do that.
public ViewResult Index(string username)
{
if (CanSeeOthersProfiles(username)) //your function to check currently logged user and his privileges
{
var model = new MyModel();
//do your logic
return View(model);
}
else
return RedirectToAction("index", "home");
}

Categories

Resources