How to get the add the query string to actionLink? - asp.net-mvc

The below link gives be the following url: http://localhost:11111/files/Details/3
#Html.ActionLink("Details", "Details", "mycontroller", new { id = item.id },null)
But I'm trying to have a url parameter like this http://localhost:11111/files/Details?id=3 or http://localhost:11111/files/Details.aspx?id=3
How do I get the actionlink to show the url like details?i=3
Here is my controller View:
public ActionResult Details(int? id)
{
...
return View();
}

Why would you like to see the parameter's name in the link?
Asp.Net MVC uses user-friendly URLs.
If you have created a project in Visual Studio using the MVC template, probally your routes, by default, are configured to interpret the parameter after the controller/action/ like the id.
So the id parameter's value in your action will be automatically replaced, by model binding, with the id number present in you URL.

The routing codes can be found under the RegisterRoutes method in the Global.asax file of our project.
I see a cookie already in the RegisterRoutes method.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults);
Using the MapRoute method above, we defined a new route.
Sample ;
public class HaberController : Controller
{
public ActionResult Listele()
{
// Listing codes will be written
return View("Listele");
}
public ActionResult Detay(string HaberId)
{
// Detail codes will be written
return View("Detay");
}
}
We go to our Global.asax file and edit it as follows.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"HaberListeleme",
"Haber",
new { controller = "Haber", action = "Listele" }
);
routes.MapRoute(
"HaberDetay",
"Haber/{id}",
new { controller = "Haber", action = "Detay" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
If we do the routing as follows:
routes.MapRoute(
"HaberDetay",
"Haber/{*Id}",
new { controller = "Haber", action = "Detay" }
);
So if we write * by putting the character next to our parameter name, it will be sent to the related parameter of the Detail method in the Controller, no matter what it says after the News / url tab.
For example:
http://www.doguhanaydeniz.com/Haber/Turkiye/Guncel/34389
If a URL is requested as Turkey / current / 34389 will be sent as a parameter.

Related

why i have to pass parameter as a querystring to Action Method in MVC?

I'm new to mvc. I'm creating a test application in mvc.
here I've studied that mvc works with url as /[Controller]/[ActionName]/[Parameters]
But in my application i have to pass parameter as /home/index?name=test. I think it should work as /home/index/test. But it doesn't work in this way.
Here is ActionMethod in homeController
public ActionResult Index(String name)
{
ViewBag.name = name;
return View();
}
Routing code in Global.asax.cs
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
);
}
Index.cshtml
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.name</h2>
Can anyone help me to findout that why its not working in /home/index/test format.
Thanks.
Routes.MapRoute(
"DefaultWithName", // Route name
"{controller}/{action}/{name}", // URL with parameters
new { controller = "Home", action = "Index", name = UrlParameter.Optional }
Because your optional parameter says "id", and in your controller it's "name".
As Lars points out, your route specifies the default parameter name as ID. Your controller specifies it as "name." If you changed your controller parameter to say, int ID, then home/index/3 would work.
As pointed by #Lars & #Joel, your route specifies the default parameter name as ID.
Declare
routes.MapRoute(
"DefaultWithName", // Route name
"{controller}/{action}/{name}", // URL with parameters
new { controller = "Home", action = "Index", name = UrlParameter.Optional });
And to use route use code
#Url.RouteUrl("DefaultWithName", new { name = "test" })
Instead of #Url.Action

ASP .Net custom route not working

ASP .Net custom route not working.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//default route
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
);
//custom route
routes.MapRoute(
"Admin",
"Admin/{addressID}",// controller name with parameter value only(exclude parameter name)
new { controller = "Admin", action = "address" }
new { addressID = #"\d+" }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
public ActionResult address(int addressID = 0)
{
//code and redirection
}
Here I want to hide everything from the url if possible...like i want to hide action name and parameter name and value if possible...
Suggest me the possible way to do this
Like I want URL like this (on priority basis)
1.http: //localhost:abcd/Admin
or
2.http: //localhost:abcd/Admin/address
or
3.http: //localhost:abcd/Admin/1
or
4.http: //localhost:abcd/Admin/address/1
for quick reference.
the custom route should appear before the default.
try naming your custom rout as null.
routes.MapRoute(
null, // Route name...
check that your calling the correct action.
if youre dealing with actions that dont recieve a parameter upon initial load(example paging)
makesure that your parameter is nullable address(int? addressID)
and on your custom route it should be like this
//custom route
routes.MapRoute(
null, //<<--- set to null
"Admin/{addressID}",// controller name with parameter value only(exclude arameter name)
new { controller = "Admin", action = "address" }
//new { addressID = #"\d+" } <<--- no need for this because based from your example " 2.http: //localhost:abcd/Admin/address" the parameter can be null.
);
thanks

URl rewriting in mvc

Hy
i had write below code
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Home", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Controller_Action", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { id = UrlParameter.Optional } // Parameter defaults
);
foreach (var route in GetDefaultRoutes())
{
routes.Add(route);
}
routes.MapRoute(
"UserPage", // Route name
"{id}", // URL with parameters
new { controller = "Home", action = "Get" } // Parameter defaults
);
}
private static IEnumerable<Route> GetDefaultRoutes()
{
//My controllers assembly (can be get also by name)
Assembly assembly = typeof(test1.Controllers.HomeController).Assembly;
// get all the controllers that are public and not abstract
var types = assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Controller)) && t.IsPublic && !t.IsAbstract);
// run for each controller type
foreach (var type in types)
{
//Get the controller name - each controller should end with the word Controller
string controller = type.Name.Substring(0, type.Name.IndexOf("Controller"));
// create the default
RouteValueDictionary routeDictionary = new RouteValueDictionary
{
{"controller", controller}, // the controller name
{"action", "index"} // the default method
};
yield return new Route(controller, routeDictionary, new MvcRouteHandler());
}
}
i am new to mvc,i want to rewrite my url somthing like this,suppose my url is like www.myhouse.com/product/index/1 then i want to display only www.myhouse.com/prduct-name for better seo performance,i am using mvc4 beta,i had also one through URL Rewriting in .Net MVC but it is not working for me....
but i don't know how to pass pass value to this method.
After lots of searching on the internet, i got my solution
add below code to global.asax
routes.MapRoute(
"Home", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"jats", // Route name
"{jats}", // URL with parameters
new { controller = "Home", action = "Content" } // Parameter defaults
);
then add below code to view:
#Html.ActionLink("test", "Content", new { jats= "test-test" })
add below code to HomeController:
public ActionResult Content(string jats)
{
return View();
}
then you done...now URL is same as you pass in query string...so your controller name and query string parameter will not display.

asp.net mvc - null parameter exception - could be routing problem?

I'm kind of new to MVC. I have a controller called PostItemsController in an area called CaseManagers with an action method called GetByUmi(int caseNumber):
[HttpGet]
public ViewResult ViewByUmi(int umi)
{
//implementation omitted
}
The routing configuration looks like this (not my work):
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
//ignore route for ico files
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?../Images/MauriceFavicon.ico(/.*)?" });
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?Images/MauriceFavicon.ico(/.*)?" });
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?Content/Images/MauriceFavicon.ico(/.*)?" });
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?/favicon.ico(/.*)?" });
//ignore javascript files routing
routes.IgnoreRoute("{file}.js");
//ignore routing for files ending .doc
routes.IgnoreRoute("{resource}.doc");
routes.MapRoute(
"CaseManagers", // Route name
"CaseManagers/PostItems/ViewByUmi/{id}", // URL with parameters
new { controller = "PostItems" } // Parameter defaults
);
//InvoicesLookUp route
routes.MapRoute(
"InvoicesLookUpShortDefault", // Route name
"InvoicesLookUp/{action}/{id}", // URL with parameters
new { controller = "InvoicesLookUp", action = "Index", area = "Home", id = UrlParameter.Optional } // Parameter defaults
,
null,
new[] { "MooseMvc.Areas.Accounts.Controllers" } // Parameter defaults
).DataTokens.Add("area", "Accounts");
//Invoices route
routes.MapRoute(
"InvoicesShortDefault", // Route name
"Invoices/{action}/{id}", // URL with parameters
new { controller = "Invoices", action = "Index", area = "Accounts", id = UrlParameter.Optional } // Parameter defaults
,
null,
new[] { "MooseMvc.Areas.Accounts.Controllers" } // Parameter defaults
).DataTokens.Add("area", "Accounts");
//administrating route
routes.MapRoute(
"AdministratorShortDefault", // Route name
"Administrator/{action}/{id}", // URL with parameters
new { controller = "Administrator", action = "Index", area = "Administrator", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
//add root route route
routes.MapRoute(
"Root",
"",
new { controller = "Home", action = "Index", id = "" }
);
When I try to call this method with the URL http://localhost:[portnumber]/CaseManagers/PostItems/ViewByUmi/1234 I get the following exception:
The parameters dictionary contains a null entry for parameter 'umi' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult ViewByUmi(Int32)' in 'MooseMvc.Areas.CaseManagers.Controllers.PostItemsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
I don't intend the ID parameter to be optional and I don't understand why MVC can't find the ID.
Can anyone tell me what I need to do?
EDIT:
Phil Haack's route tester is telling me that the following route is being mapped:
routes.MapRoute(
"CaseManagers", // Route name
"CaseManagers/PostItems/ViewByUmi/{id}", // URL with parameters
new { controller = "PostItems" } // Parameter defaults
);
But it is being mapped AFTER another route CaseManagers/{controller}/{action}/{id}. But this route isn't anywhere in the Global.asax file (take a look, it's reproduced in full above).
Any idea what's going on?
Method parameters in ASP.NET MVC match up 1-1 with route parameters. Since you have no routes that take in a route value named umi, no route will catch what you're trying to do.
You have one of two choices:
If you want the default route to handle that action, then change:
public ViewResult ViewByUmi(int umi)
{
//implementation omitted
}
to:
public ViewResult ViewByUmi(int id)
{
//implementation omitted
}
However, if you want to keep umi(because it has contextual meaning that makes that code easier to follow), then you want to add a route to explicitly deal with it:
//UMI route
routes.MapRoute(
"umi",
"/case/postitems/view/{umi}",
new { area = "CaseManager", controller = "PostItems", action = "ViewByUmi", umi = "" }
);
Turns out that Global.asax isn't the only place that routing happens. Each of the areas in this application has its AreaRegistration class. I added a new route to the top of this class to produce the following:
public class CaseManagersAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "CaseManagers";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"PostItems", // Route name
"CaseManagers/PostItems/ViewByUmi/{umi}", // URL with parameters
new { area = "CaseManagers", controller = "PostItems", action = "GetByUmi", umi = "{umi}" } // Parameter defaults
);
context.MapRoute(
"CaseManagers_default",
"CaseManagers/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
The routing debugger now tells me this is getting matched first. Now I just need to work out why I've got an error telling the the resource cannot be found...
You don't have a route for CaseManagers/PostItems/ViewByUmi/1234 and it would appear that it is taking ViewByUmi and try to convert it to an System.Int32 because it is falling into the Default route. If you create a Route for your CaseManagers you should no longer have this problem.
Use Phil Haacks' Route Debugger to help you out :o)
routes.MapRoute(
"CaseManagers", // Route name
"CaseManagers/PostItems/ViewByUmi/{id}", // URL with parameters
new { controller = "PostItems" } // Parameter defaults
);

Parameter value not passed in ASP.NET MVC route

I'm learning about creating custom routes in ASP.NET MVC and have hit a brick wall. In my Global.asax.cs file, I've added the following:
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
);
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
}
The idea is for me to able to navigate to http://localhost:123/home/filter/mynameparam. Here is my controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Filter(string name)
{
return this.Content(String.Format("You found me {0}", name));
}
}
When I navigate to http://localhost:123/home/filter/mynameparam the contoller method Filter is called, but the parameter name is always null.
Could someone give a pointer as to the correct way for me to build my custom route, so that it passes the name part in the url into the name parameter for Filter().
The Default route should be the last one.
Try it this way:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// My Custom Route.
routes.MapRoute(
"User_Filter",
"home/filter/{name}",
new { controller = "Home", action = "Filter", name = String.Empty }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
I believe your routes need to be the other way round?
The routes are processed in order, so if the first (default, OOTB) route matches the URL, that's the one that'll be used.

Resources