asp.net mvc routing url.action issue - asp.net-mvc

In my view I'm using a
<img src="#Url.Action("Method", new { Model.Url })" ...
<img src="#Url.Action("Method", new { Model.Url })/1" ...
And in that method I have params:
public ActionResult Method(string url, int ids=0)
With
var book = GetBookByUrl(url);
...
switch (ids)
{
case 1:
In my global.asax I have:
routes.MapRoute(null,
"{controller}/{action}/{url}/{ids}",
new { controller = "Controller", action = "Method", url = "", ids = #"\d+" });
My view returns the correct URL's (with /1 and /2 appended), but I can't seem to get my method to retrieve the value of ids so that I can manipulate them in my action method to retrieve different results based on the Url.Action URL provided within my view, what gives?
The ids parameter seems to always be 0 (not being routed data) and the url parameter has the entire url "bla-bla/2", which I do not want.
Please note that although there are plenty of routing resources, I've read over them and can't seem to get this to work - also is this the standard way of routing data from a request to a controller?
Please show me by way of example how to solve, many thanks!

Related

Reload page but get a 404 error because of wrong url when routing in MVC

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&param2=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.

MVC4 Razor Appending ID to a url using route.config

I just cant achieve my goal of getting an id to appear in a URL. Here is an example of what I have done so far.
Here is my BlogController:
public ActionResult BlogPost(int hiddenBlogId)
{
TempData["id"] = hiddenBlogId;
return View(_repository);
}
Here is my route.config:
routes.MapRoute(
"MyBlog", // Route name
"blog/{action}/{id}", // URL with parameters
new { controller = "Blog", action = "blogpost", id = #"0|-?[1-9]\d*" } // Parameter defaults
);
I am completely missing the point somewhere. How can I pick up the parameter which went into my method/action BlogPost and then display it in the output URL.
http://www.mydomain/controller/id
It's so that in the end I should be able to display the title for each blog. I'm using an ID just for simplicity for now. Any help at all would be greatly appreciated.
Your route definition says that the third value is called id, but you are trying to bind hiddenBlogId in the method. The two names need to match. Change the hiddenBlogId action method parameter to id, or map a new route with the {hiddenBlogId} placeholder.

MVC .NET 4 MapRoute + ActionLink or RouteLink issue

Okay, so here's the deal. I've got controller called "Hotel" with view called "Index", where I'm trying to produce code allowing me to generate links in form of:
../Hotel?id=1
with ID passed as argument. To do so, I've tried using MapRoute:
#Html.RouteCollection.MapRoute("Hotel", "../{controller}/{id}", new { controller = "hotel" });
together with ActionLink:
#Html.ActionLink("More >>>", "", "Hotel", new { id = item.HotelId }, null)
But the outcome link goes like this:
Hotel/Index/1
Which leads to correct location, but burns visual consistency of all links at my website. I've tried RouteLink as well, but with no success.
Thanks in advance!
Do you want to make all links in the application use the standard querystring format for parameters named "id"? If so, removing the {id} from url and defaults object in the "Default" route should do that for you just fine.
If you want to limit it to the "Hotel" controller, you are on the right track w/ the custom route. First, make sure the custom route comes before the default route definition, and second, define it with nothing beyond the controller/action like:
routes.MapRoute(
"HotelRoute", // Route name
"Hotel/{action}/", // URL with parameters
new { controller="Hotel", action = "Index" } // Parameter defaults
);
Any params you pass in should then be appended to the query string as a name/value pair.

Customizing the url-from-parameters lookup in asp.net mvc

I have a route added by the code
routes.MapRoute("MyRoute", "TheUrl", new { controller = "MyController", action = "MyAction" });
I can then do a reverse lookup with the arguments like UrlHelper.Action("MyAction", "MyController"), and it will return a nice url like ~/TheUrl
However, for this route I want the generated URL to be ~/TheUrl?p=2354, with the parameter being some versioning parameter. Is there a way of doing this by mapping the route with some customized route handler or something? The versioning parameter will be non-standard and require some custom code to execute every time the Url is looked up.
I think a UrlHelper extension method would be most ideal and simple here specially.
public string MyRoute(this UrlHelper url)
{
string versionNumber = GetVersionNumber(); // or w/e is required to get it
return Url.Action("MyAction", "MyController") + "?p=" + versionNumber;
}
This would make calling that route much easier in html
<%= Url.MyRoute() %>

In ASP.NET MVC, preserve URL when return RedirectToAction

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.

Resources