Mvc: Exclude id from url - asp.net-mvc

I have the next foreach in my cshtml page, it allows to me iterate in each Model item
#foreach (var item in Model)
{
<div class="date">
#item.pubDate
</div>
<a href="#Url.RouteUrl("Details", new { action = "Details", controller = "News", id = item.id, title = item.title })">
<img src="some route" alt="some alt" />
</a>
}
so now it's working fine and each element inside foreach loop has an url with something like
http://something.com/News/Details/1/first-title
http://something.com/News/Details/2/second-title
It's possible create urls with something like
http://something.com/News/Details/first-title
http://something.com/News/Details/second-title
but i can still sending id parameter to my controller ?
Thanks in advance

Add another route:
routes.MapRoute(
name: "NewsTitleRoute",
url: "News/Details/{id}/{title}",
defaults: new {
controller = "News",
action = "Details",
id = UrlParameter.Optional,
title = UrlParameter.Optional
}
);
In your controller declare the details method like this, with the two parameters as optional:
public ActionResult Details(int? id, string title="")
{
}
That route configuration and Details method will work for:
http://something.com/News/Details/
http://something.com/News/Details/1
http://something.com/News/Details/first-title
http://something.com/News/Details/1/first-title

You can just pass the title property for id parameter.
#Url.RouteUrl("Details",
new { action = "Details", controller = "News", id = item.title})
Then set type of id parameter as string in your action method:
public ActionResult Details(string id)
Or you can create custom route like in von-v's answer. Just make sure it's above the default route.

Related

Multiple route values to the controller in MVC

I have a got a problem while passing parameters to the controller
Here is my view:
#model IEnumerable<WebApplication2.Models.Distributer>
#foreach (var item in Model) {
#Html.ActionLink("Edit", "Edit", new{id=item.DistributerID,user=item.Name })
}
My Controller
public ActionResult Edit(int? id,string name)
{
ViewBag.name = name;
}
In the Edit view just to display the name.
My RouteMap
routes.MapRoute(
name: "Route1",
url: "{controller}/{action}/{id}/{user}",
defaults: new { controller = "Distributers", action = "Edit", id = UrlParameter.Optional,user="" }
);
Here I find that variable name in the controller is null.Inorder to test the route works.I pull the link from the loop,ie;
#model WebApplication2.Models.Distributer
#Html.ActionLink("Edit", "Edit",new{id=item.DistributerID,user=Model.Name})
This works Fine..string name=value(not null)
Why is it so??
The parameter in your route and in your call to Html.ActionLink is user, but on your action method signature, it's name. In other words, user is being passed, but your action method does nothing with it. Conversely, the name parameter is never provided. Make sure that the parameter name lines up everywhere and you're golden.

MVC Routes, adding a filter to existing page

I have a route:
context.MapRoute(
"ISPCCodeSearch_default",
"OnlineOrder/{controller}/ISPCCodeSearch/{ISPC}",
new
{
area = "OnlineOrder",
controller = "Home",
action = "ISPCCodeSearch",
ISPC = UrlParameter.Optional,
});
that brings up a number of products by a product code eg,
OnlineOrder/Home/ISPCCodeSearch/11011/
I want to further filter this by brand by clicking on a filter link on the above page.
OnlineOrder/Home/ISPCCodeSearch/11011/Xerox
How do I generate the links and the route?
<a class=" list-group-item" href='#(Url.Action("BrandFilter", new {brand = item.BrandName}))'>
#item.FriendlyBrandName <span class='badge'>#item.BrandItemsCount</span>
</a>
I have the above code which just gives me :
/BrandFilter/Xerox
I don't know how to implement this.
You will need to update route:
context.MapRoute(
"ISPCCodeSearch_default",
"OnlineOrder/{controller}/ISPCCodeSearch/{ISPC}/{param2}",
new
{
area = "OnlineOrder",
controller = "Home",
action = "ISPCCodeSearch",
ISPC = UrlParameter.Optional,
param2= UrlParameter.Optional,
});
And for a link, just add another property:
#(Url.Action("BrandFilter", new {brand = item.BrandName, prop2 = item.property2}))

Routing issue with MVC

I'm working with MVC 3 and have an issue. Instead of giving mydomain/mydirectory/item like I expected I get this:
mydomain/mydirectory/list?animal=quack.
Here's the route in the global
//Default route mapping
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = #"[^\.]*", action = #"[^\.]*" }
);
Code showing how I'm building the link:
<div id="main-content" title="AnimalBox" style="float:none;">
<% Html.DataList(Model.PriceListAnimals).Columns(7).Item(item =>
{
item.Template(galleryImage =>
{%>
<div style="margin-left:20px; line-height:150%;">
<span><%= Html.ActionLink(galleryImage.AnimalName,"List",new { #animal = galleryImage.AnimalName }) %></span>
</div>
<% });
}).Render(); %>
</div>
Any ideas?
You have to define a route for special case routing like your instance. Since you are passing 'animal' as a parameter, you should create a route to handle that instance. In your global.aspx (above the default route), create something like below:
routes.MapRoute(
"Animal", // A distinct Route name
"{controller}/{action}/{animal}", // URL with parameters
new { controller = "MyDirectory", action = "List"}
);
This will define a route to the MyDirectory controller on the action list which has an animal parameter which is NOT OPTIONAL. Defining routes is what enables you to generate clean URLs from the html helpers and other methods (redirect to action, etc).
The overload for Html.ActionLink is:
Html.ActionLink("linkText", "actionName", "controller", object routeValues, object HtmlAttributes)
From what you've said, mydirectory = controller, and List = action, correct? If so, try:
<%= Html.ActionLink(galleryImage.AnimalName, "List", "mydirectory", new { #id = galleryImage.AnimalName }, null) %>
this should produce:
quack

ASP.NET MVC Routing and Structure

I have a Customer list that will have Invoices and Emails linked to it.
I have my customer/details/1 and customer/edit/1 working as per the default route but would like to have it instead be like below
customer - Lists customers
customer/1/edit - Edit Customer ID 1
customer/1/details - Details of Customer ID 1
customer/1/invoice - Invoice List for Customer ID 1
customer/1/invoice/3 - Details of Invoice ID 3 for Customer ID 1
I setup the following route (before the default route)
routes.MapRoute("CustomerActions",
"customer/{customerid}/{action}/{id}",
new { controller = "customer", action = "details", id="" }
);
Which seems to work, but in my customer edit view I have an ActionLink like
<%=Html.ActionLink("Back to List", "Index") %>
But it gives the URL
/customer/1/index rather than just /customer or /customer/index
You can try with two routes :
routes.MapRoute("Customer",
"customer/{customerid}/{action}/{id}",
new { controller = "customer", action = "details", id="" }
);
routes.MapRoute("Customers",
"customer",
new { controller = "customer", action = "List" }
);
And as for the link :
<%=Html.RouteLink("Back to List", "Customers", null) %>
Did you try
"{controller}/{action}/{id}",
// new { controller = "Customer", action = "Details", id = ""}
No need for the customer to be present in your routemap.
your route is "customer/{customerid}/{action}/{id}"
you specify action = "Index", it takes customerid from the current request (in your case, 1)
and we have /customer/1/index
/customer/1 would be controller="customer", customerid = 1, action="details" according to your defaults
/customer will not match the route, cause you do not have defaults for customerid

How to get the ID from URL?

I am using asp.net MVC.
I have edit page url like {controller}/Edit/2
so on the view page how can I get the ID from this URL?
I'm gonna put a link to redirect to some page with sending above ID.
EDIT
Like
<%=Html.ActionLink("name", "Action", "Controller", new{ ID = ? } ) %>
you can get it from the RouteData object
<%=Html.ViewContext.RouteData.Values["id"].ToString() %>
Put the ID in the ViewData in your action method, then your view can access the value from the ViewData.
Controller: ViewData["ID"] = id;
View: <%=Html.ActionLink("name", "Action", "Controller", new{ ID = (int)ViewData["ID"]} ) %>
...in view you get info in the model to show data so you have id in model then you can get id and pass id easy
call Model in View :
#model IEnumerable<NewsWebsite.Models.Blog>
foreach (var item in Model)
{
//your code
#Html.ActionLink("Edit", "Edit", new { id = item.BlogID })
}
Or
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
//Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable
I know of two ways: You can create your link and use the "ViewData" property to pass the link to your view or you can stronglyType the ViewPage.
Here is a link on strongly typing the view.

Resources