I'm used to generating route URLs to other controller actions within an MVC controller action using something similar to below:
public class ApplicationController : Controller
{
public ActionResult Index( )
{
var url = Url.RouteUrl("routename",
new { controller = "Application", Action = "Index2" , other="other" });
}
public ActionResult Index2( string other)
{
}
}
But I also need to be able to generate URLs to MVC controller actions from within webapi too, How would I go about doing this?
There seems to be a UrlHelper property on the APIController but I cant find any examples of how to use this and have not been able to figure it out myself.
UPDATE :
The reason I am trying to generate a url is that this particular webapi method sends an email which provides the recipient with a link to direct the user back to an appropriate section of the site. I obviously want to get away from hardcoding this as it will not work for different deployments and also if I begin changing the routing this link will be broken. Is there a better approach to doing this?
You can use MVC route names as well with web API UrlHelper. Example,
Url.Link("Default", new { Controller = "Account", Action = "Login" });
or
Url.Route("Default", new { Controller = "Account", Action = "Login" });
Related
My View is called Survey.cshtml. My current url is http://localhost:17471/Campaign/Survey/6184.
In this page I have a drop down menu to select language. There are English and Spanish. One I select the language, I want to reload the page because some context are shown in different language. I still want to keep the same url.
My code in Survey.cshtml.
$("#id").change(function () {
var selectedValue = $(this).find('option:selected').text();
window.location.href = "#Url.Action("Survey1", "Campaign", new {id=Model.SurveyModel.CampaignId, languageName = "languageToken" })".replace("languageToken", selectedValue);
});
However it goes to the url http://localhost:17471/Campaign/Survey1/6184?languageName=Spanish
My controller CampaignController.cs has the methods.
public ActionResult Survey(int id)
{
// omitted code
return View(model);
}
[HttpPost]
public ActionResult Survey1(int id, string languageName)
{
// omitted here
var view = "Survey";
return View(view,model);
}
I don't have Route for the above methods in RouteConfig.cs. I am not very strong on MVC Routing. Sometimes I am confused the old-and-good HTTP URL ENCODING with the http://site-address/page.html?param1=value1¶m2=value2 and the MVC ROUTING which uses the form of http://site-address/page/value1/value2.
So help me.
Your Survey1 action is decorated with [HttpPost], which means you have to use the POST method from your client. But when you do a redirect with window.location.href, that always uses the GET method. You have two options:
Change your controller action and remove [HttpPost].
Create a form with the POST method and your values in it, and use javascript to trigger the submit event on that form instead of using window.location.href.
I'm a kind of newbie with routing, I want to give the possibility to my user to go to the admin part of the site by just entering www.hisSite.com/admin whith a route that will redirect to the SiteAdmin controller and Index action. Is it possible?
I probably didn' understand something but I'm baddly stuck....
There are a few options that you can choose such as redirecting or creating a separate Area for the admin side however I think since you're a newbie just create a controller called AdminController and include an action called Index like below:
public class AdminController : Controller
{
public Action Index()
{
// Some action
}
}
To call this you'd only need to enter:
www.hisSite.com/admin
or
www.hisSite.com/admin/index
What's happening here is by using a convention of adding Controller suffix to each controller class, routing will recognise the first part i.e. Admin as a route when requested by a browser.
routes.MapRoute(
name: "Admin",
url: "admin/{action}/{id}",
defaults: new { controller = "SiteAdmin", action = "Index", id = UrlParameter.Optional }
This will route all urls pointing to www.hisSite.com/admin to actions and views in the SiteAdmin controller.
A simpler way is to just create a Admin controller ofcourse.
So, I've read through tutorials and books about MVC routing as well as played with it on my projects and come to a pretty solid understanding of how to use it to accomplish what I want to with it.
But, I'm up against something I can't quite figure out yet.
What I want to accomplish is a unique url for each client that doesn't look like "http://mysite.com/client/1". This url would take the browser to the Client Controller, Index action, ClientId = 1...obviously.
What I'd like to do is have a URL like "http://mysite.com/Acme" that would do a database lookup to figure out which client has the unique name of "Acme", and then redirect the request to the Client Controller, Index view and set the ClientId to whatever it is on the client with the name 'Acme'.
The default route keeps catching it and can't handle it.
Any ideas?
I recommend using an Global Action Filter to accomplish this or you can create a route with a static path that will route to your lookup controller (e.g., /lookup/{companyname} will route to your database lookup controller).
How about "http://www.mysite.com/Clients/{ClientName}"
routes.MapRoute(null, "Clients/{ClientName}", new{controller = "Clients", action = "Index"};
public class ClientsController : Controller
{
public ActionResult Index(string clientName)
{
var id = Db.GetClientIdBy(clientName);
// do your redirect...
}
}
Or have I missed the point?
I have a rather archaic login system, and this is part of the login action:
// login action
return RedirectToAction("Action", new {
id = aVal,
name = aName,
// other params
});
It redirects the user to the Action action, and i noticed that name and the other params ended up being part of the final url scheme. I need to pass all those values to Action.
[HttpGet]
public ActionResult Action(int id, string name, ...) {
Is it possible to pass them to Action and having the url like this: /Controller/Action/123.
I need to restrict the Action method to only those who pass through the login action, the long url + query string make it almost impossible to make it through, but is there another more profesional way to do it.
Thanks and greetings to the SO and SE community.
In order to get Restful styled url's you need to setup an appropriate route.
So in your case something like
routes.MapRoute("MyRoute", "MyController/MyAction/{id}/{name}", new { controller = "MyController", action = "MyAction" });
you can see some other examples here
The second part of your question is more vague - you may want to tag your class with an [Authorize] attribute and then override OnAuthorization where you can do any checks. Not sure if this is what you are looking for.
There is an example of this here
I have an action method, and depending on what is passed to it, I want to redirect to another action in another controller. The action and controller names are determined at run time.
If I return RedirectToAction(), it will force a redirect and change the URL in the browser. What I would like is something like TransferToAction() that can transfer processing of the current request to another action, without doing a redirect. I seem to remember a method behaving like this in earlier previews, but I can't seem to find it in the RC of ASP.NET MVC.
Do you know how I would do this?
UPDATE
I added the following route:
routes.MapRoute(
"PageRouter",
"{site}/{*url}",
new { controller = "PageRouter",
action = "RoutePage", site = "", url = "" }
);
And the PageRouter controller action RoutePage:
public ActionResult RoutePage(string site, string url)
{
var controller = new HomeController {ControllerContext = ControllerContext};
controller.RouteData.Values["controller"] = "Home";
controller.RouteData.Values["action"] = "Index";
return controller.Index(site, url);
}
I had to set the controller and action in RouteData for the Home Index view to be rendered. Otherwise, it would look for an Index view in PageRouterController.
I still need to figure out how to create a controller and its action knowing only their names. e.g. I'd like to be able to just call something like this:
public ActionResult RoutePage(string site, string url)
{
return InvokeAction("Home", "Index");
}
What should go in InvokeAction() ? Do I need to pass it any context?
You should be able to just call the other method directly and, assuming that it returns a ViewResult, it will render that view in response to the request and the url will not change. Note, you'll be responsible for making sure that all of the data that the other method needs is available to it. For example if your other method requires some form parameters that weren't provided, you may need to construct a suitable FormCollection and set the ValueProvider of the controller to a ValueProvider based on your FormCollection. Likewise with any arguments required by the method.