Pass query string parameter to UrlHelper.Action method in .net mvc - asp.net-mvc

I have method like
UrlHelper.Action("login", "Authentication", HttpContext.Current.Request.Url.Scheme);
I want to pass query string parameter like "referrer?" = pageName to this method. How can I do it?

You just have to decalre your parameter like this:
UrlHelper.Action("login", "Authentication", new { referrer = "Page Name" })
Then get the parameter in your Action:
Request.Params["referrer"]

Example
Url.Action("GetValues", "Home", new { Area = "Solan", id =Model.Id})
Here Area and id are the parameters passed to the GetValues method inside Home controller

Related

ASP.NET MVC5 , Url parameter And Get method

Does using RouteData.Values is the right way to get the Url parameter from GET method?
for example the url : http://www.mywebsite.com/Product/Search/Apple
In the controller, the method parameter won't bind the url parameter as POST method do.
Or something i can do, so whether POST or GET, the parameter will auto bind to method paramether?
The Route:
context.MapRoute(
"Product_Search",
"{controller}/{action}/{Keyword}",
new { controller = "Product", action = "Search", Keyword = "" }
);
The Controller:
[HttpGet]
public ActionResult Search(string keyword) //< the keyword here is null
{
string keyword = Convert.ToString(RouteData.Values["SearchText"]); //<keyword here is fine = 'Apple'.
// Do search
return View("SearchResult", viewModel);
}
Model binding will work with GET and POST. Looks like your keyword parameter has a lowercase k. Your route definition uses uppercase K. If you fix these inconsistency it should work.

RedirectToAction method with multiple route parameters not redirecting

I am using RedirectToAction method and i want to pass two route parameters
but its not redirecting to specified action method.
I am using following code:
return RedirectToAction("abcd", "Registration", new { id = "", loginType = "pqr" });
and the specified action method signature is as :
public ActionResult abcd(string id, string loginType = null)
Is there any mistake in signature??
Thanks...
Make sure that the abcd() action method is in a class called RegistrationController. If your abcd() action method is in the RegistrationController class then you want to call like this:
return RedirectToAction("abcd", new { id = "", loginType = "pqr" });

Mvc: pass id but not show it in friendly url

I have a view that renders a list of news, in that i have an href tag, and i need to call a Detail method and pass it the news id, now i have a querystring in my url like that
News/Details?id=x... but i need something like News/Details/Category/Title-of-something, a friendly url with news category, name and without the id
this is my action, it works but i get that querystring
foreach (var item in Model)
{
Read More
}
I was trying with something like, with a Url.RouteUrl
routes.MapRoute(
name: "Details",
url: "{controller}/{action}/{id}/{category}/{newsName}",
defaults: new { controller = "News", action = "Details"}
);
but it never goes to Details actionresult, and also i need to pass the id parameter for showing some news Details, but i don't want to display it in the friendly url. Im really confused how to achieve it. Thanks in advance
Try this:
#Html.RouteLink("Read More", "Details", new { action = "Details", id = item.newsId, category = item.categoryName, newsName = item.newsName })
Use :
Read More
Make sure your route is not overridden by other route. So put your route first in RoutConfig.cs
Change your code to:
foreach (var item in Model)
{
Read More
}//change name=item.newsName to newsName=item.newsName
Also make sure that your controller has correct signature as per your routing details:
public class NewsController : Controller
{
public ActionResult Details(int id, string category, string newsName )
}
First URL Correct
Read More
You may Route Debugger whenever yo see issue related to routes

Using HtmlHelper.BeginForm to match a complicated route

I have a complicated route that I would like to match with an HtmlHelper.BeginForm method. I've read quite a few articles and answers on using route value dictionaries and object initializers and html attributes. But they all fall short of what I want to do...
Here is the route I want to match:
// Attempt to consolidate all Profile controller actions into one route
routes.MapRoute(
"Profile",
"{adminUserCode}/{controller}s/{customerId}/{action}/{profileId}",
new { adminUserCode = UrlParameter.Optional, controller = "Profile"},
new { adminUserCode = #"\d+", customerId = #"\d+", profileId = #"\d+" }
);
An example url for the controller & action I want to match with this would be:
http://mysite.com/123/Profiles/456/UpdatePhoneNumber/789
With the actual phone number being in the POST body
And here is the closest syntax I've come to getting right:
#using (Html.BeginForm(
"UpdatePhoneNumber",
"Profile",
new {
customerId = Model.LeadProfile.CustomerId,
profileId = Model.CustomerLeadProfileId
}))
{
<!-- the form -->
}
But this puts the parameters in the object as query string parameters, like this:
<form method="post"
action="/mvc/123/Profiles/UpdatePhoneNumber?customerId=78293&profileId=1604750">
I just tried this syntax on a whim, but it output the same thing as the other overload
#using (Html.BeginForm(new
{
controller = "Profile",
customerId = Model.LeadProfile.CustomerId,
action = "UpdatePhoneNumber",
profileId = Model.CustomerLeadProfileId
}))
I know I can just fall back on raw HTML here, but there seems like there should be a way to get the silly HtmlHelper to match more than the most basic of routes.
If you want to use complicated routes in your form you need to use the BeginRouteForm Method
#using (Html.BeginRouteForm("Profile", new
{
controller = "Profile",
customerId = Model.LeadProfile.CustomerId,
action = "UpdatePhoneNumber",
profileId = Model.CustomerLeadProfileId
}))

ASP.Net MVC Route to Username

I am trying to create a route with a Username...
So the URL would be mydomain.com/abrudtkhul (abrudtkhul being the username)
My application will have public profiles based on usernames (Ex: http://delicious.com/abrudtkuhl). I want to replicate this URL scheme.
How can I structure this in ASP.Net MVC? I am using Membership/Roles Providers too.
Here's what you want to do, first define your route map:
routes.MapRoute(
"Users",
"{username}",
new { controller = "User", action="index", username=""});
What this allows you to do is to setup the following convention:
Controller: User (the UserController type)
Action: Index (this is mapped to the Index method of UserController)
Username: This is the parameter for the Index method
So when you request the url http://mydomain.com/javier this will be translated to the call for UserController.Index(string username) where username is set to the value of javier.
Now since you're planning on using the MembershipProvider classes, you want to something more like this:
public ActionResult Index(MembershipUser usr)
{
ViewData["Welcome"] = "Viewing " + usr.UserName;
return View();
}
In order to do this, you will need to use a ModelBinder to do the work of, well, binding from a username to a MembershipUser type. To do this, you will need to create your own ModelBinder type and apply it to the user parameter of the Index method. Your class can look something like this:
public class UserBinder : IModelBinder
{
public ModelBinderResult BindModel(ModelBindingContext bindingContext)
{
var request = bindingContext.HttpContext.Request;
var username = request["username"];
MembershipUser user = Membership.GetUser(username);
return new ModelBinderResult(user);
}
}
This allows you to change the declaration of the Index method to be:
public ActionResult Index([ModelBinder(typeof(UserBinder))]
MembershipUser usr)
{
ViewData["Welcome"] = "Viewing " + usr.Username;
return View();
}
As you can see, we've applied the [ModelBinder(typeof(UserBinder))] attribute to the method's parameter. This means that before your method is called the logic of your UserBinder type will be called so by the time the method gets called you will have a valid instance of your MembershipUser type.
You might want to consider not allowing usernames of certain types if you want to have some other functional controllers like Account, Admin, Profile, Settings, etc. Also you might want your static content not to trigger the "username" route. In order to achieve that kind of functionality (similar to how twitter urls are processed) you could use the following Routes:
// do not route the following
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("content/{*pathInfo}");
routes.IgnoreRoute("images/{*pathInfo}");
// route the following based on the controller constraints
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
, new { controller = #"(admin|help|profile|settings)" } // Constraints
);
// this will catch the remaining allowed usernames
routes.MapRoute(
"Users",
"{username}",
new { controller = "Users", action = "View", username = "" }
);
Then you will need to have a controller for each of the tokens in the constraint string (e.g. admin, help, profile, settings), as well as a controller named Users, and of course the default controller of Home in this example.
If you have a lot of usernames you don't want to allow, then you might consider a more dynamic approach by creating a custom route handler.
You could have a route that looks like:
{username}
with the defaults of
Controller = "Users"
For the finished product of:
routes.MapRoute(
"Users",
"{username}",
new { controller = "Users" }
So that the Username is the only url parameter, the MVC assumes it passes it to the users controller.
Are you trying to pass it as a parameter to a Controller?
Theoretically you could do something like this:
routes.MapRoute("name", "{user}/{controller}/{action}", new { controller = "blah", action = "blah", user = "" })
I'm not too experienced with ASP.NET routing, but I figure that should work.
routes.MapRoute(
"Users",
"{username}",
new { controller = "Users", action="ShowUser", username=""});
Ok, what this will do is default the username parameter to the value of {username}
so even though you've written username="" it'll know to pass the value of {username} .. by virtue of the strings match.
This would expect
for the url form
http://website.com/username
Users Contoller
ShowUser Action (method in controller)
username parameter on the ShowUser action (method)

Resources