Asp.net MVC Routing w/ string parameter - c#

I'm learning asp.net, and can't solve a rather simple problem for a while.
Have the RouteConfig.cs file with the following content:
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
And got the controller with the content:
...
[Route("image/show/{uuid}")]
public ActionResult Show(string uuid) {
return View(uuid);
}
...
And the result when I try to open this url
Thanks in advance for the response!

Its your following line creating issue
return View(uuid);
This line taking the ViewResult View(string viewName) overload of controller. It is considering the uuid variable you passed-in as a viewname and tries to find the view file by that name.
As a workaround you can change that line to
return View((object)uuid);
This will take correct overload ViewResult View(object model)
or store the uuid in viewbag and return the view as
return View();
off course, you still need Show.cshtml file in your View/Image directory.

The error says that it cannot find the cshtml file in Views/Images/sdfsd.cshtml.
Add that file and it should work

Related

Route prefix is not working with index

I have controller: DoomPlaceController
In route: I have used: doom-place/{parameter} // no action
and In controller :
[Route("doom-place/{parameter}")]
public ActionResult Index(string parameter)
{
return View();
}
What I want: when I hit URL: www.xyz.com/doom-place
it should open Doom-Place/index page.
But right now, I am able to access the page with doom-place/index but I want when I hit www.xyz.com/doom-place, it will automatically open index page.
Help will be appreciated.
You can make the parameter optional
[RoutePrefix("doom-place")]
public class DoomPlaceController : Controller {
//Matches GET /doom-place
//Matches GET /doom-place/some_parameter
[HttpGet]
[Route("{parameter?}")]
public ActionResult Index(string parameter) {
return View();
}
}
Given that attribute routing is being used, the assumption is that attribute routing has been enabled in RouteConfig.RegisterRoutes
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
//enable attribute routing
routes.MapMvcAttributeRoutes();
//covention-based routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Reference Attribute Routing in ASP.NET MVC 5

How do I get ASP.NET to route a controller properly?

I have this in my controller:
public ActionResult Details(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Sales saleRecord = new Sales();
var result = saleRecord.GetSalesOrderHeader((int)id);
return View(result);
}
However if I browse to /ControllerName/Details/5 I get this error:
"Server Error in '/' Application. - The view 'details' or its master was not found or no view engine supports the searched locations."
The strange thing is that if I use ASP.NET Scaffolding to generate a view, the Details part of that works fine. It's basically the same code I have above as well.
Here's my RouteConfig.cs, if that's relevant:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
So why is that the scaffolding controller works fine, without having anything specific added to RouteConfig, yet my controller Details method is not working?
There should be more detail in error that what locations have been searched. Did you put break point in controller and checked if its being hit?
try
return View((object)result);
instead of
return View(result)
cause its calling overload View(string viewName)
If this doesn't work, try to specify viewName explicitly like this:
return View("ViewName", name);
Additionally, check your folder structure. MVC looks for views (like Index) under the views folder but they also have to be under a folder named after their controller (except partial views).

MVC to web form redirection without changing URL

my requirement is, there will be one controller method, which will handle all the request, that might return MVCview/model, or it might return .ASPX page, in any case URL must be same.
something like following.
public ActionResult HandleRequest()
{
if(Module is Converted)
{
return view(ModuleName);
}
else
{
//return module.aspx page, Here I can user Redirect method but it will change URL
//I don't want browser's Url to be changed.
}
}
Your answer is Routing.
http://msdn.microsoft.com/en-us/library/cc668201.aspx
Look at following code :
public ActionResult Test()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return RedirectToAction("TestAspx");
}
public ActionResult TestAspx()
{
ViewBag.Message = "Your app Test aspx page.";
return View();
}
Here the action TestAspx() returns an TestAspx.aspx view.
And for the Routing
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"TestAspx",
"testganesh",
new { controller = "Home", action = "TestAspx" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
Please make appropriate changes to the routing names that you need.
Hope this will help.
Let me know if you still face any issue.
Mark as right if the issue got fixed.
:)

Custom URL Routing in Asp.Net MVC 4

How can i do like this url (http://www.domain.com/friendly-content-title) in Asp.Net MVC 4.
Note: This parameter is always dynamic. URL may be different: "friendly-content-title"
I try to Custom Attribute but I dont catch this (friendly-content-title) parameters in ActionResult.
Views:
Home/Index
Home/Video
ActionResult:
// GET: /Home/
public ActionResult Index()
{
return View(Latest);
}
// GET: /Home/Video
public ActionResult Video(string permalink)
{
var title = permalink;
return View();
}
RouteConfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Home Page",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Video Page",
url: "{Home}/{permalink}",
defaults: new { controller = "Home", action = "Video", permalink = "" }
);
}
What should I do for catch to url (/friendly-content-title)?
To enable attribute routing, call MapMvcAttributeRoutes during configuration. Following are the code snipped.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
In MVC5, we can combine attribute routing with convention-based routing. Following are the code snipped.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
It is very easy to make a URI parameter optional by adding a question mark to the route parameter. We can also specify a default value by using the form parameter=value. here is the full article.
Radim Köhler's solution is a good one.
But another option if you want more control over routing is using a custom constraint.
Here's an example
RouteConfig.cs
routes.MapRoute(
"PermaLinkRoute", //name of route
"{*customRoute}", //url - this pretty much catches everything
new {controller = "Home", action = "PermaLink", customRoute = UrlParameter.Optional},
new {customRoute = new PermaLinkRouteConstraint()});
So then on your home controller you could have action like this
HomeController.cs
public ActionResult PermaLink(string customRoute)
{
//customRoute would be /friendly-content-title..do what you want with it
}
The magic of this happens in the IRouteConstraint that we specified as the 4th argument in the MapRoute call.
PermaLinkRouteConstraint.cs
public class PermaLinkRouteConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values,
RouteDirection routeDirection)
{
var permaRoute = values[parameterName] as string;
if (permaRoute == null)
return false;
if (permaRoute == "friendly-content-title")
return true; //this indicates we should handle this route with our action specified
return false; //false means nope, this isn't a route we should handle
}
}
I just wanted to show a solution like this to show you can basically do anything you want.
Obviously this would need to be tweaked. Also you'd have to be careful not to have database calls or anything slow inside the Match method, as we set that to be called for every single request that comes through to your website (you could move it around to be called in different orders).
I would go with Radim Köhler's solution if it works for you.
What we would need, is some marker keyword. To clearly say that the url should be treated as the dynamic one, with friendly-content-title. I would suggest to use the keyword video, and then this would be the mapping of routes:
routes.MapRoute(
name: "VideoPage",
url: "video/{permalink}",
defaults: new { controller = "Home", action = "Video", permalink = "" }
);
routes.MapRoute(
name: "HomePage",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
Now, because VideoPage is declared as the first, all the urls (like these below) will be treated as the dynamic:
// these will be processed by Video action of the Home controller
domain/video/friendly-content-title
domain/video/friendly-content-title2
while any other (controllerName/ActionName) will be processed standard way

rout registration breaks when I change the url in global.asax

The following rout registration works for my asp.net MVC application
routes.MapRoute("TrackingChannels", "TrackingChannels/{action}",
new { controller = "TrackingChannels", action = "Index" });
When I change it to catch this url,
I get resource not found error
for localhost:85\dis\TrackingChannels
routes.MapRoute("TrackingChannels", "Dis/TrackingChannels/{action}",
new { controller = "TrackingChannels", action = "Index" });
How can I fix this?
Alright, I need to go out so I'll post this now as I don't know how long I'll be.
I setup a default MVC 3 project and changed the routing to match your case.
Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"TrackingChannels",
"Dis/TrackingChannels/{action}",
new { controller = "TrackingChannels", action = "Index" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Added a TrackingChannelsController:
public class TrackingChannelsController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Test()
{
return View();
}
}
I deliberately added the Test action to see if /dis/trackingchannels/{action} would also work. Then I added a couple of views which resulted in the following project structure:
Finally, here's the results of specifying the URLs in the browser:
First with /dis/trackingchannels:
Second with /dis/trackingchannels/test:
The only thing I can say without seeing your project is to double check the URL is matching the correct route. To do that you can use Phil Haack's RouteDebugger.

Categories