Url for pages in ASP.NET MVC4 - asp.net-mvc

Ok.is it possible to set url for the pages of type "localhost:5454/user/details/1" to localhost:5454/somenameofuser .. can i do it in mvc4? "somenameofuser" is an url for concrete page. I want to set this field to the class user. and this field would unikalnym..thanks for the help!

What is it you are trying to achieve? Explain it further. But as for my understanding, You could try and create a routing that will match a url of /somenameofuser
routes.MapRoute (
"Default", // Route name
"/{nameofuser}", // URL with parameters
new { controller = "Controller here", action = "Action here" } // Parameter defaults
);

Related

MVC Routing Parameter Precedence

I came across a scenario where I had the default MVC Route setup. Like So.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Then navigating to a url as such
domain/controller/action/1234
On this page I was then navigating to the same page but with different parameters after a certain event. Like so.
var id = $(this).data("id");
var url = "#Url.Action("action", "controller", new { area = ""})";
var params = $.param({id: id, vrnsearch: true});
var fullUrl = url += "?" + params;
window.location.href = fullUrl;
I noticed that the url was still keeping the same id in the url and attaching parameters like so.
domain/controller/action/1234?id=4321&vrnsearch=true
Now my question is, is there a way to determine a precedence over if it should use the value for id from the url or from the parameter.
I have actually found a work around/fix for my issue by using the below, which removes the id from the url and just uses parameters.
#Url.Action("action","controller", new {id = "", area = ""})
However was just curious if there is a precedence in parameters vs url routing.
The query string has nothing at all to do with routing (at least, not unless you customize routing to consider it).
The values that are passed to the ModelBinder and to your action method are done so by Value Providers. You can control the order of precedence by changing the order in which their corresponding ValueProviderFactory is registered in the static ValueProviderFactories.Factories property.
As you can see, the default configuration is to first use the RouteDataValueProviderFactory and if it returns no value it will try the QueryStringValueProviderFactory. If you change the order of the factories, the order of precedence changes.
ValueProviderFactories.Factories.RemoveAt(3);
ValueProviderFactories.Factories.Insert(4, new RouteDataValueProviderFactory());

MVC routes.MapRoute name property

I'm brand new to MVC so please bear with me as I'm only on the second page of the MS Tutorial (see last code example). For the HelloWorldController the following MapRoute is added:
routes.MapRoute(
name: "Hello",
url: "{controller}/{action}/{name}/{id}");
I'm just wondering, is it purely the pattern matching that does the work and the name "Hello" is just for my own reference? If so, are there not naming conventions that should be followed saying the MapRoute should be called HelloWorldWelcome, where welcome is a method inside the HelloWorldController.cs (see above link). Or am i being pedantic?
The route name is also used by the UrlHelper class. For example:
var url = Url.Route("Hello", new
{
controller = "SomeController",
action = "SomeAction",
name = "charlie",
id = 123
});
This will generate a matching URL.
This feature is much more useful when you use Attribute Routing. For example, if on some controller you have an action:
[RoutePrefix("api/phonebook")]
public class PhonebookController
{
[HttpGet("contact/{id}", Name = "GetContact")]
public Contact GetContact(int id)
{
...
}
}
In other code you could use Url.Route("GetContact", new { id = 7 }) to generate the URL /api/phonebook/contact/7.
Please refer to details on ASP.NET MVC Routing Overview
Name attribute is for callign a route from your views or controller with route name.
From ActionLink your can use a routename:
Html.RouteLink("link_text", "route_name", route_parameters)
The question seems to be not so clearly answered (how the "Hello" route is choosen by the "HelloWorld" controller?), but as an Asp.Net MV5 begginer, I can see that the route is selected by default according to the match between the router url property and the URL parameters.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "ImageScan", action = "ScanImage", id = UrlParameter.Optional },
namespaces: new[] { "WebApplication3.Controllers" }
);
I am finding error :
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Views/ImageScan/ScanImage.cshtml

Default Routing Not working in .NET MVC 1 (and 2)

My default routes are very simple, but the page doesn't properly load without fully qualifying the entire route.
Here are the routes I'm using:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
Here's the only action in the application in a HomeController:
public ActionResult Index()
{
return Content("New stuff");
}
With these URLs:
http://localhost:8081/NewMvc1/
I get The incoming request does not match any route.
With:
http://localhost:8081/NewMvc1/Home
http://localhost:8081/NewMvc1/Home/Index
I get a 404 Mvc page that says it tried to handle the request with a static file.
Yet, finally with a 'fully qualified url'
http://localhost:8081/NewMvc1/Home/Index/1
I get the expected result output from the one and only one action.
New Stuff
This doesn't seem right at all. I've also been getting Failed to Execute Action from this same application (not sure if that's related).
I've used Phil Haack's RouteDebugger to get this far, which pointed out that it wasn't matching the URL when the Optional parameters were missing, but did when those parameters were provided.
You're missing the id from your defaults:
new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Accept url as parameter in MVC action?

I'm using ASP.NET MVC 3 and I would like to accept url as parameter for one of the action. But, I'm getting "HTTP Error 400 - Bad Request." error for the below example. How do I resolve this issue?
Example:
http://localhost:8343/http://google.com
Global.asax.cs:
routes.MapRoute(
"Default", // Route name
"{hostUrl}", // URL with parameters
new { controller = "Home", action = "Index", hostUrl = UrlParameter.Optional } // Parameter defaults
);
You need to use URL encoding for the parameter http://google.com.
So, navigate here:
http://localhost:8343/http%3A%2F%2Fgoogle.com
(I just used an online URL encoder tool.)
Use
HttpUtility.UrlEncode
or
Server.URLEncode
Depending where you are doing the encoding.
I fixed by following these steps.
Change Web project properties to "Use IIS Local Server" and check "Use IIS Express"
Add the following setting in Web.config inside :
<httpRuntime requestPathInvalidCharacters=""/>

ASP.NET MVC 2 One Route Works, One Route Doesn't

I have two routes in my ASP.NET MVC application.
The first is working fine - it's an ActionResult that returns a view.
The second is on the same controller and is an ActionResult that returns a Json response. It takes a couple of additional paramaters.
This second route is working on my dev machine, but when I deploy it to the server I get back a blank response. Any suggestions will be gratefully received.
I have also copy-pasted the route into a browser to eliminate any issues in the jQuery JavaScript.
The method
[HttpGet]
public ActionResult CheckSku(string id, string brand) {
CheckSkuModel model = new CheckSkuModel();
model.Id = id;
model.Brand = brand;
return Json(model, JsonRequestBehavior.AllowGet);
}
The routes
routes.MapRoute(
"Default", // Route name
"{controller}.mvc/{action}/{id}", // URL with parameters
new {
controller = "Orders", action = "Send", id = ""
} // Parameter defaults
);
routes.MapRoute(
"CheckSku", // Route name
"{controller}.mvc/{action}/{id}/{brand}", // URL with parameters
new {
controller = "Orders", action = "CheckSku", id = "", brand = ""
} // Parameter defaults
);
Two thing you can quickly check that may help:
1. Swap the two routes around so "CheckSku" is above "default"
2. Make the "CheckSku" more specific so will look something like:
routes.MapRoute(
"CheckSku", // Route name
"Orders.mvc/CheckSku/{id}/{brand}", // URL with parameters
new {
controller = "Orders", action = "CheckSku", id = "", brand = ""
} // Parameter defaults
);
that was another controller doesn't pick up the url by mistake.
An alternative is the use the routelink helper when generating the url so it points to the correct route.
When you say you "get back a blank response", do you mean you're not getting an error, but that the server isn't returning anything? What makes you think this is a routing issue?
Some troubleshooting tips:
Use Fiddler to examine the HTTP request you're making and the raw HTTP response the server is sending back. If you're getting a 500 response code then check the response for error information.
Can you attach a remote debugger to the server? This might give you a chance to investigate any exceptions that are raised.

Resources