Use #Html.actionlink - Calling an actioncontroller of another View - asp.net-mvc-3

I am struggling to call an action in a View to another View actioncontroller by passing to it a parameter.
This is the call from the View (I am in the index View and call the Account controller):
#Html.ActionLink("parameters", "MyParameters", "Account", new { email = "test" })
My runtime compiler is saying "cannot resolve action MyParameters" what' s wrong with it ?
This is the function from my account controller:
public ActionResult MyParameters(string email) {}
This is my route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Paramètres par défaut
);
}
Cheers

Try:
#Html.ActionLink("parameters", "MyParameters", "Account", null, new { email = "test" })
The overload is:
#Html.ActionLink("linkText", "actionName", "controller", object routeValues, object HtmlAttributes)
routeValues is for adding a query string on the link. So for example, if you wanted to add id=1 to the link, your action link would look like this:
#Html.ActionLink("parameters", "MyParameters", "Account", new { #id = 1 }, new { email = "test" })
this would produce the following:
parameters
if you want email as a querystring you need to do this:
#Html.ActionLink("parameters", "MyParameters", "Account", new { #id = 1, #email = "test" }, null)
this will produce:
parameters

There is no ActionLink overload that takes 3 strings and an object. http://msdn.microsoft.com/en-us/library/dd505040
The code is probably trying to interpret "Account" as routeValues and your parameters as htmlAttributes. I'm guessing if you take a look at the link that's actually output you'll see it doesn't look like you'd expect.

Try:
#Html.ActionLink("Controller", "Action", new { email = "test",
parameters = "parameters" })
Your controller:
public ActionResult MyParameters(string email, string parameters) {}

Related

MVC3 links SEO - how to make calls from one controller to other controller

I have one problem, I am not sure how to explain but I will try.
I followed this: http://www.deliveron.com/blog/post/SEO-Friendly-Routes-with-ASPnet-MVC.aspx
And I was able to achieve what they describe.
But if I have a page where i wish to call action from other controller, it doesn't work.
It doens't show the link in this way: "this-is-my-link" in the URL.
I don't know what do I do wrong?
in Global.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default2",
"{controller}/{action}/{id}/{pageTitle}",
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional,
pageTitle = UrlParameter.Optional
}
);
}
Views/Help/FAQ
#Html.ActionLink(FaqStrings.ContactUs, "ContactUs", "Home", new { id = 1, pageTitle = "link text".ToSeoUrl() })
It says that it can't resolve the ContactUs. Instead of the actions from HomeController, it sees the actions of the HelpController.
In HomeController
[AllowAnonymous]
public ActionResult ContactUs()
{
var model = new ViewModelContactUs
{
Resultmessage = string.Empty,
Youremail = string.Empty,
Yourmessage = string.Empty,
Yourname = string.Empty
};
return View(model);
}
[AllowAnonymous]
[HttpPost]
public ActionResult ContactUs(ViewModelContactUs model)
{
Log.DebugFormat("HomeController-ContactUs()");
........
var model2 = new ViewModelContactUs
{
......
};
ModelState.Clear();
return View(model2);
}
Try moving your controller into the RouteValues dictionary part of your #Html.ActionLink
#Html.ActionLink(FaqStrings.ContactUs, "ContactUs", new {controller="Home", id = 1, pageTitle = "link text".ToSeoUrl() })
EDIT
To address the logic, it has to do with the available signatures of the Html.ActionLink method. Here is the MSDN for information but...
The method signature that you were using was Html.ActionLink("Link Text", "Action", "Contoller", RouteValues, HtmlAttributes). Since you were not passing HtmlAttributes, it was matching up wrong and generating the wrong link. By either moving the controller into the RouteValuesDictionary or passing a , null at the end of your call should solve it. But, I personally don't like throwing nulls around unless I need to, so I typically just define the controller in the RouteValuesDictionary.
If you were not passing any RouteValues, then a call to Html.ActionLink("Link Text", Action, Controller) works with no issues.
Hope that clears it up a little! :)
The underlying problem is that:
#Html.ActionLink(FaqStrings.ContactUs,
"ContactUs",
"Home",
new { id = 1, pageTitle = "link text".ToSeoUrl() })
Will produce an Anchor which when clicked will produce an HTTP GET, however you're method is requiring HTTP POST:
[AllowAnonymous]
[HttpPost] // <-----POST
public ActionResult ContactUs(ViewModelContactUs model)

Url.Action MVC3 not recognizing route parameter when building link

When adding custom routing constraints to my route parameters I am finding that it is breaking the Url.Action method I use to build my links. If the route constraint is simply a regular expression then the Url.Action method continues to recognize the parameter, however if it is a custom constraint which I define, Url.Action method gives my parameter as a request parameter.
Here is my route definition:
routes.MapRoute(
"Event",
"Events/{strDate}",
new { controller = "Events", action = "Index", strDate = DateTime.Today.ToString("yyyy-MM-dd") },
new { strDate = new IsValidDateConstraint() },
new[] { "MyProject.Controllers" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "MyProject.Controllers" }
);
The IsValidDateConstraint class inherits from IRouteConstraint and returns true or false if the strDate parameter parses correctly to a DateTime object:
public class IsValidDateConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
{
DateTime dt = new DateTime();
if (DateTime.TryParse(values["strDate"].ToString(), out dt))
return true;
}
return false;
}
}
Using the Url.Action method to build URL's:
#Url.Action("Index", "Events", new { strDate = ViewBag.CurrentDate.AddDays(1).ToString("yyyy-MM-dd") })
The resulting link is: /Events?strDate=2012-08-15
Everything routes correctly if I type in /Events/2012-08-15, it's just that the Url.Action method is not recognizing that strDate is a parameter defined in my route only when I apply my custom routing constraint. If I comment out the custom routing constraint then the Url.Action method maps the URL correctly.
Any ideas on why the Url.Action is not recognizing my route parameter when I have a custom route constraint defined?
You haven't shown how your IsValidDateConstraint looks like but make sure you are doing a culture invariant parsing for the yyyy-MM-dd format:
public class IsValidDateConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
DateTime date;
return DateTime.TryParseExact(
values[parameterName] as string,
"yyyy-MM-dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date
);
}
}
Also make sure that this route is placed before the default route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Event",
"Events/{strDate}",
new { controller = "Events", action = "Index", strDate = DateTime.Today.ToString("yyyy-MM-dd") },
new { strDate = new IsValidDateConstraint() },
new[] { "MyProject.Controllers" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
also DateTime.Parse(ViewBag.CurrentDate.ToString()) looks a wee-bit of a WTFkish code. If ViewBag.CurrentDate is already a DateTime you could directly write:
#Url.Action(
"Index",
"Events",
new {
strDate = ViewBag.CurrentDate.AddDays(1).ToString("yyyy-MM-dd")
}
)
Obviously a much better solution is to use view models:
#Url.Action(
"Index",
"Events",
new {
strDate = Model.CurrentDate.AddDays(1).ToString("yyyy-MM-dd")
}
)
UPDATE:
Now that you have shown your code the problem comes from the if condition you have put in your constraint:
if (routeDirection == RouteDirection.IncomingRequest)
When using the Url.Action helper this condition is never satisfied. Only when resolving an incoming url. So you will have to remove it if you want this constraint to work with url helpers.

How to get url parameter from current route in asp.net mvc?

I have a route like this:
http://localhost/c/61/legetoj
its defined as:
routes.MapLocalizedRoute("Category",
"c/{categoryId}/{SeName}",
new { controller = "Catalog", action = "Category", SeName = UrlParameter.Optional },
new { categoryId = #"\d+" },
new[] { "Nop.Web.Controllers" });
Now, on all the pages having this url, I want to get SeName value (here is `legetoj')
In my view (header) I've tried this with: ViewContext.RouteData.Values["SeName"]
but it returns empty..
Do you know what I am doing wrong?
Just set up an action with the same name parameter as you would like to accept such as:
public ActionResult Category(int categoryId, string SeName) {
// do stuff
}
It should automatically insert that value inside the variable.

ASP.net MVC routing with optional first parameter

I need to provide following functionality for one of the web sites.
http://www.example.com/[sponsor]/{controller}/{action}
Depending on the [sponsor], the web page has to be customized.
I tried combination of registering the routes with Application_Start and Session_Start but not able to get it working.
public static void RegisterRoutes(RouteCollection routes, string sponsor)
{
if (routes[sponsor] == null)
{
routes.MapRoute(
sponsor, // Route name
sponsor + "/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
}
Also, the default behavior without [sponsor] should also function.
Can someone please let me know if it is technically feasible to have an optional first parameter in the MVC3 URL. If yes, please share the implementation. Thank you.
Updated Code
After making the changes as suggested by Sergey Kudriavtsev, the code works when value is given.
If name is not provided then MVC does not route to the controller/action.
Note that this works only for the home controller (both and non-sponsor). For other controllers/actions, even when sponsor parameter is specified it is not routing.
Please suggest what has to be modified.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"SponsorRoute",
"{sponsor}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"NonSponsorRoute",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, sponsor = string.Empty }
);
}
Action Method
public ActionResult Index(string sponsor)
{
}
In your case sponsor should not be treated as a constant part of URL, but as a variable part.
In Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
...
routes.MapRoute(
"SponsorRoute",
"{sponsor}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"NonSponsorRoute",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, sponsor=string.Empty }
);
...
}
In your controllers, for example, HomeController.cs:
namespace YourWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string sponsor)
{
// Here you can do any pre-processing depending on sponsor value, including redirects etc.
}
...
}
}
Note that type of this parameter will always be System.String and the name of route template component {sponsor} must exactly match the name of action parameter string sponsor in your controllers.
UPD: Added second route for non-sponsor case.
Please note that such setup will complicate your logic, because you might confuse different urls, for example URL
http://www.example.com/a/b/c
could be matched by both routes: first one will have sponsor=a, controller=b and action=c; second one will have controller=a, action=b and id=c.
This situation can be avoided if you specify more strict requirements to URLs - for example, you may want IDs to be numerical only. Restrictions are specified in fourth parameter of routes.MapRoute() function.
Another approach for disambiguation is specifying separate routes for all of your controllers (usually you won't have much of them in your app) before generic route for sponsors.
UPD:
Most straightforward yet least maintainable way to distinguish between sponsor and non-sponsor routes is specifying controller-specific routes, like this:
public static void RegisterRoutes(RouteCollection routes)
{
...
routes.MapRoute(
"HomeRoute",
"Home/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, sponsor=string.Empty }
);
routes.MapRoute(
"AccountRoute",
"Account/{action}/{id}", // URL with parameters
new { controller = "Account", action = "Index", id = UrlParameter.Optional, sponsor=string.Empty }
);
...
routes.MapRoute(
"SponsorRoute",
"{sponsor}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
...
}
Note that here all controller-specific routes must be added before SponsorRoute.
More complex yet more clean way is implementing RouteConstraints for sponsor and controller names as described in answer from #counsellorben.
In my case, I've resolved this issue using the following two routers:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "MultiCulture",
url: "{culture}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { culture = new CultureConstraint(CultureFactory.All.Select(item => item.UrlPrefix).ToArray()) }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
}
}
Where CultureConstraint class looks like below:
public class CultureConstraint : IRouteConstraint
{
private readonly string[] values;
public CultureConstraint(params string[] values)
{
this.values = values;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary routeValues, RouteDirection routeDirection)
{
string value = routeValues[parameterName].ToString();
return this.values.Contains(value);
}
}
And MultiCultureMvcRouteHandler like this:
public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
{
var culture = CultureManager.GetCulture(requestContext.RouteData);
if (culture != null)
{
var cultureInfo = new CultureInfo(culture.Name);
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
}
return base.GetHttpHandler(requestContext);
}
}
In addition to adding a second route before the default route, as Sergey said in his answer, you also must add a RouteConstraint to the initial route, to enforce that the {sponsor} token is the name of a valid sponsor.
You can use the RouteConstraint in this answer: Asp.Net Custom Routing and custom routing and add category before controller
Remember that you must also enforce a rule that a sponsor name cannot be the same as any of your controller names.
i will show you in simple example you don't have to change in Route.config.cs
only you have to do in Route.config.cs just put in
Optional URI Parameters First and Default Values
Route.config.cs
routes.MapMvcAttributeRoutes();
Controller
[Route("{Name}/Controller/ActionName")]
public ActionResult Details(string Name)
{
// some code here
return View();
}
Results
localhost:2345/Name/controllername/actionname/id(optional)

URL Routing: How do I have a string as my id?

I would like to receive a string as the id in the URL. Here is an example:
http://www.example.com/Home/Portal/Fishing
I would like to have Fishing in my id. But I cannot achieve it with the following code:
Code from my Controller:
public ActionResult Portal(string name)
{
// some code
ViewData["Portal Name"] = name;
}
Code from Global.asax.cs:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Just change the argument to id:
public ActionResult Portal(string id)
{
// some code
ViewData["Portal Name"] = id;
}
The argument will be bound if it has the same name as the route value token. So an alternate approach would be to keep the argument named name and change the route:
public ActionResult Portal(string name)
{
// some code
ViewData["Portal Name"] = name;
}
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{name}", // URL with parameters
new { controller = "Home", action = "Index", name = UrlParameter.Optional } // Parameter defaults
);
I would choose using id, though, as it's the more standard approach.

Resources