ASP.NET MVC - keep links to the root folder - asp.net-mvc

I am trying to link inside the same folder, I have the following structure
/Home/Index
/Home/About
/Home/Contact
When I start the webpage, I link to the Index, so I get the webpage on the screen: www.example.com.
Now I would like to link to another page so I get: www.example.com/Contact.html (or even better I would like to get www.example.com/Contact) however I get www.example.com/Home/Contact.
I use this as an action link:
<li class="pure-menu-item pure-menu-selected">#Html.ActionLink("Contact us", "Contact", "Home")</li>
This is my route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What could I change to get the desired result?

Decorate you Contact action with a RouteAttribute and pass it the desired route as parameter (i.e. "Contact")
Edit
Here's an example HomeController using the RouteAttribute:
public class HomeController
: Controller
{
public IActionResult Home()
{
return this.View();
}
[Route("Contact")]
public IActionResult Contact()
{
return this.View();
}
}
Note that you can use the RouteAttribute on Controllers, too. For instance, if I added a Route("Test") attribute on the HomeController, all of my controllers actions would look like: "/Test/[ActionRoute]".
In your views, you can use the following syntax, instead of using the old #Html.ActionLink tag helper:
<li class="pure-menu-item pure-menu-selected">
<a asp-controller="Home" asp-action="Contact">Contact Us</a>
</li>
In my opinion, those attribute tag helpers are way cleaner and html friendly ;)

i was able to fix it with some good reading and searching and this is what i came up with:
i added this to the routeConfig for each link to a html page:
routes.MapRoute("Index", "Index", new { controller = "Home", action = "Index" });
routes.MapRoute("About", "About", new { controller = "Home", action = "About" });
routes.MapRoute("Contact", "Contact", new { controller = "Home", action = "Contact" });
and instead of using an action link i use a route link:
<li class="pure-menu-item">#Html.RouteLink("About us", "About")</li>
this gives the desired result: www.example.com/About

Related

How to use query string in asp.net mvc layout page

I am getting confuse in understanding the query string and routing concept in asp.net mvc, and I will appreciate if some one can please help.
My problem is:
I have a login page where user will enter the Username, password and Id. After successful login I like to take the Id and pass it to my Profile page. Now profile page is part of layout page along with two other links.
<nav class="main">
<ul class="menu" >
<li>#Html.ActionLink("Profile", MVC.Profile.Index(), new { Id = Request.QueryString["Id"].ToString() })</li>
<li>#Html.ActionLink("Configuration", MVC.Configuration.Index(),new { Id = Request.QueryString["Id"].ToString() })</li>
<li>#Html.ActionLink("Transaction", MVC.Transaction.Index(), new { Id = Request.QueryString["Id"].ToString() })</li>
</ul>
</nav>
From my login page I am using the following code to Redirect the user to Profile page.
return RedirectToAction("Index", "Profile", new { Id =
viewModel.Id });
Now how can i pass the same value to configuration and transaction page, they are just action links on layout page.I thought of using Request.QueryString like below:
new { Id = Request.QueryString["Id"].ToString()
but this is throwing object reference exception.
my routing look like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional });
Thanks in advance.
So after you are redirecting to the Index action of your Profile controller, make sure your action takes in a int parameter like below and return it to the Profile view:
public ActionResult Index(int id)
{
return View(id);
}
Render your links in the Profile's Index view like below:
#model int
<nav class="main">
<ul class="menu" >
<li>#Html.ActionLink("Profile", "Index", new { Id = #Model })</li>
<li>#Html.ActionLink("Configuration", "Index",new { Id = #Model })</li>
<li>#Html.ActionLink("Transaction", "Index", new { Id = #Model })</li>
</ul>
</nav>
Let me know if you need more clarification.

.net MVC4 Form submit generates ? instead of / in url -- wrong routing?

i'm kinda new to asp.net mvc4 and try to get some practise now. after some research about routing i still got a problem to pass parameters after a form submit.
my form looks like this:
#using (Html.BeginForm("Index", "Resplaner", FormMethod.Get, new { name = "navigation", id = "navigation" }))
{
<select name="id" size="15" id="nav_menu">
#foreach (var categorie in Model.Categories)
{
<optgroup label="#categorie.Name">
#foreach (var ressource in Model.Ressources)
{
if (#categorie.Id == ressource.Type)
{
<option value="#ressource.Id">#ressource.Name</option>
}
}
</optgroup>
}
</select>
}
which is submitted by the following java script:
$('#nav_menu').on('click', function (event) {
if ($(event.target).is("option")) {
var form = $(event.target).parents('form');
form.submit();
}
});
my actual routes are configurated like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Resplaner",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Resplaner", action = "Index", id = UrlParameter.Optional }
);
so my problem is right now that my generated url after the form submit looks like this
http://localhost:62456/Resplaner?id=6
but my desired url look should look like this
http://localhost:62456/Resplaner/Index/6
if i type the second url manually to my browser, the correct result is shown... thats why i guess there is something wrong in the way how i submit my form. or my routes are still messing up.
i already did some example tutorials about forms in mvc4 but they are always used in a different case like my. so i would be happy about a helping hand.
i am thankful for every help :)
greetings Kurn
Here goes my solution -
Have your html like this -
#using (Html.BeginForm("Index", "Resplaner", new { name = "rami", id = "1" }, FormMethod.Get))
{
// ....
}
Then have a route this way -
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{action}/{name}/{id}",
defaults: new { controller = "Resplaner", action = "Index" }
);
Then your jquery hits the form submit, your URL is going to be -
And the URL is going to be - http://localhost:5738/Resplaner/Index/rami/1?
NOTE: If you do not want that Question mark at the end, then make a POST instead of GET.
The other solution would be to use Hidden Fields -
#using (Html.BeginForm("Index", "Resplaner", FormMethod.Get))
{
#Html.Hidden("id", "1");
#Html.Hidden("name", "rami");
<input type="submit" value="click"/>
}
But again this approach will give you - http://localhost:5738/Resplaner/Index?id=1&name=rami
One more Alternative is to create a #Html.ActionLink() with the required URL and make it click in jquery.
Ok fixed it on another way.
To fix my actual problem i just added a new action in my Controller which receive the form parameter with the question mark and simply do a redirect to the desired url.
[HttpGet]
public ActionResult IndexMap(String id = "1")
{
return RedirectToAction("Index", "Resplaner", new { id = id });
}
It may be not the best way to do it because of the second server call. but for my project i dont see any performance issues since it will be only used in an intranet.
http://localhost:62456/Resplaner/IndexMap?id=2 will redirect to http://localhost:62456/Resplaner/Index/2
I would like to thank everyone who tried to help me. You gave me some great suggestions and ideas.

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

How to hide the home controller path in action links

Using the out of the box MVC application the action links under the Home controller are rendered as follows
#Html.ActionLink("Home", "Index", "Home") > /
#Html.ActionLink("About", "About", "Home") > /Home/About
How do i make all action links that falls into the HomeController to hide the "Home" in the link paths.
e.g
#Html.ActionLink("About", "About", "Home") > /About
#Html.ActionLink("Contact", "Contact", "Home") > /Contact
#Html.ActionLink("Sitemap", "Sitemap", "Home") > /Sitemap
#Html.ActionLink("Terms", "Terms", "Home") > /Terms
Thanks
You can set the controller in your route part and remove it from the url. Something like this:
routes.MapRoute("", "/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
Look at this answer also.
You can create different routes in the RouteConfig class as followed:
routes.MapRoute(
name: "AboutUs",
url: "about-us",
defaults: new { controller = "Home", action = "AboutUs" }
);
This way, when the URL is /about-us it's going to call the AboutUs action in Home controller.

#Html.ActionLink not Rendering as Expected

I have this in my Global.asax.cs:
routes.MapRoute(
"User",
"User/{username}/{action}",
new { controller = "User", action = "Index", username = "*" }
);
Then on my _Layout.cshtml I have this code:
<ul id="menu">
#if (!String.IsNullOrEmpty(Context.User.Identity.Name))
{
<li>#Html.ActionLink("Home", "Home", new { controller = "User" }, new { username = Context.User.Identity.Name })</li>
}
</ul>
</div>
</div>
The thing is, it will render the link properly the first time it swings through here. (Link will be /User/rob/Home where "rob" is a username. If I navigate elsewhere on the page and then click back on my link, the link is rendered as /User/*/Home. When I step through the code, Context.User.Identity.Name is correct every time.
Am I missing something really basic here? I'm not sure what to search for.
That's exactly what you should expect given that route. You don't specify username in the route values dictionary but in the HTML attributes, so it takes the default from the route, *. You should be using the signature that allows you to specify both the controller and the action as strings with additional route values in the dictionary.
#if (!String.IsNullOrEmpty(Context.User.Identity.Name))
{
<li>#Html.ActionLink("Home", "Home", "User" new { username = Context.User.Identity.Name }, null )</li>
}

Resources