Customizing Routes in ASP.NET MVC4 - asp.net-mvc

When executed Search Controller - Index
public ActionResult Index(string parm1, string parm2)
Currently URL shows /Search/Index?parm1=aa&parm2=bb
I want to show /Search/aa/bb
I changed the mapRoute to:
routes.MapRoute(
name: "SearchList",
url: "Search/{action}/{parm1}/{parm2}",
defaults: new
{
Controller = "Search",
action = "Index",
parm1= UrlParameter.Optional,
parm2= UrlParameter.Optional
});
what am I missing?

Here's just a straight forward approach to make url change with search term. This is not out of the box and it won't have any exact binding to your route table, if you changed your route, then you have to manually fix it in the javascript. Also you may need to do some null/empty check when generating the url.
$("input.search_term").change(function (e){
//Get search terms and build new url
var parm1 = $("input.search_term[name='parm1']").val();
var parm2 = $("input.search_term[name='parm2']").val();
var newUrl = "/search/"+ parm1 + "/" + parm2;
//Change the link url, can do same thing on a form action url as well
$("a.search_link").attr("href",newUrl);
//For showing the text below, not necessary
$("b.t_link").html(newUrl);
});
<input type="text" class="search_term" name="parm1" value="aa" />
<input type="text" class="search_term" name="parm2" value="bb" />
<a class="search_link" href="/search/aa/bb">Search</a>
<!--not necessary-->
<br />
<span>URL of the link will be: <b class="t_link"></b></span>
<!--I assume you use jquery, let me know if you don't-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Try this:
routes.MapRoute(
name: "SearchList",
url: "Search/{parm1}/{parm2}",
defaults: new
{
Controller = "Search",
action = "Index",
parm1 = UrlParameter.Optional,
parm2 = UrlParameter.Optional
});

Related

Display query string in specific format in mvc form

when we submit form with get method, it pass parameters as querystring like below:
http://localhost:2564/Blog?SearchManufacturer=land
But, I want to display query string like below:
http://localhost:2564/Blog/SearchManufacturer/land
I have tried below code. but still it passing with query string.
#using (Html.BeginForm("Index", "Blog", new { CurrentFilter = Model.SearchManufacturer }, FormMethod.Get))
{
<div class="form-group col-lg-4 col-md-6 col-sm-6 col-lg-12">
<label>Search Manufacturer</label>
#Html.TextBoxFor(x => x.SearchManufacturer, new { #class = "form-control" })
</div>
<div class="form-group col-lg-4 col-md-6 col-sm-6 col-lg-12">
<input type="submit" value="Search" class="submit" />
</div>
}
also, in route.config, I have used different combinations of routing as below.
routes.MapRoute("Blog", "Blog/SearchManufacturer/{SearchManufacturer}", defaults: new { controller = "Blog", action = "Index" });
routes.MapRoute("BlogbyPageSortandFilter", "Blog/Page/{page}/CurrentFilter/{currentFilter}/SortBy/{sort}", defaults: new { controller = "Blog", action = "Index" });
routes.MapRoute("BlogbyPageandSort", "Blog/Page/{page}/SortBy/{sort}", defaults: new { controller = "Blog", action = "Index" });
routes.MapRoute("BlogbyPageandFilter", "Blog/Page/{page}/CurrentFilter/{currentFilter}", defaults: new { controller = "Blog", action = "Index" });
routes.MapRoute("BlogbySortandFilter", "Blog/SortBy/{sort}/CurrentFilter/{currentFilter}", defaults: new { controller = "Blog", action = "Index" });
routes.MapRoute("SortBlog", "Blog/SortBy/{sort}", defaults: new { controller = "Blog", action = "Index" });
routes.MapRoute("BlogbyPage", "Blog/Page/{page}", defaults: new { controller = "Blog", action = "Index" });
routes.MapRoute("BlogbyFilter", "Blog/CurrentFilter/{currentFilter}", defaults: new { controller = "Blog", action = "Index" });
these routing are used for sorting, paging, filtering using Pagedlist.mvc. all these are working fine. but searching is not passing parameter as in routing. it is passing parameter as query string.
please help me to fix this.
Thanks
Lalitha
If your form method is set to GET type, when you submit the form, form data will be appended to the action attribute url as querystring values (which starts with ?). This is something the browsers does. Your asp.net mvc routing cannot do anything on this.
If you absolutely need the /Blog/SearchManufacturer/land url when the form is submitted, you can hijack the form submit event with client side javascript and update the url however you want. The below code will give you the output you want.
$(function () {
$("#searchFrm").submit(function (e) {
e.preventDefault();
var formAction = $(this).attr("action");
if (!formAction.endsWith('/')) {
formAction += '/';
}
var url = formAction +'SearchManufacturer/'+ $("#SearchManufacturer").val();
window.location.href = url;
});
});
Assuming your form tag has an Id value "searchFrm"
#using (Html.BeginForm("Index", "Blog",FormMethod.Get,new { id="searchFrm"}))
{
// Your existing code goes here
}

How do i make any value display on the address bar when on get request?

i have the following view
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using( Html.BeginForm("Create", "Concepts", new { name="sfsfsfsfsf", gio="sfsf9s9f0sffsdffs", ford="mtp"}, FormMethod.Get, null ) )
{
<input type="submit" name="name" value="New" />
}
when i click the new button how do i show the values gio, ford and name on the URL?
this is my route definition
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 }
);
}
You usage of BeginForm() is adding 3 route values, not query string values. If you want to generate a url which is .../Concepts/Create/sfsfsfsfsf/sfsf9s9f0sffsdffs/mtp which would go to (in ConceptsController)
public ActionResult Create(string name, string gio, string ford)
Then you need to add the following route definition (and it needs to be before the Default route
routes.MapRoute(
name: "Create",
url: "Concepts/Create/{name}/{gio}/{ford}",
defaults: new { controller = "Concepts", action = "Create" }
);
Note also that you need to remove name="name" from your submit button because of the conflict with the route parameter
Alternatively, if you want .../Concepts/Create?name=sfsfsfsfsf#&gio=sfsf9s9f0sffsdffs&ford=mtp, then remove the route parameters and add inputs for the values
#using( Html.BeginForm("Create", "Concepts", FormMethod.Get) )
{
<input name="name" value="sfsfsfsfsf" />
<input name="gio" value="sfsf9s9f0sffsdffs" />
<input name="ford" value="mtp" />
<input type="submit" value="New" />
}

ASP.NET MVC Search Results Page MapRoute Doesn't Work

How can i set mapRoute for search results page? My code doesn't work.
Global.asax.cs
routes.MapRoute(
name: "SearchResults",
url: "{action}/{Keyword}",
defaults: new { controller = "Home", action = "Search" }
);
Search Form
#using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
#Html.TextBox("Keyword",null , new { #class = "SearchBox" })
<input type="submit" value="Search" />
}
HomeController.cs
public ActionResult Search(string Keyword)
{
GamesContext db = new GamesContext();
var SearchResults= (from i in db.Games where i.GameName.Contains(Keyword) || i.GameDesc.Contains(Keyword) select i).Take(20).ToList();
return View(SearchResults.AsEnumerable());
}
This one works for me (should be before default route):
routes.MapRoute(
"SearchResults",
"Search/{Keyword}",
new { controller = "Search", action = "SearchAction" }
);
Creating an ActionLink and MapRoute that there is a constant name in it
And there's a point to use new controller for search instead of home with this route.

.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.

In MVC3, how can I create a route like mydomain.com/chigago and hit that route from a GET form?

I have an application that shows locations on a map. I have created a route so that I can have nice hackable URLs, like http://www.mydomain.com/paris. This works fine just typing in the URL, but I have a search form on the home page that sends a GET request. When the form is submitted, the URL displayed in the location bar is in the format http://www.mydomain.com/Dashboard?location=paris. Normally this wouldn't matter too much as it's hitting the correct action, but I have a backbone.js application running the show and it's particular about the URL structure.
It may be impossible to do what I need without javascript or a redirect, because the location isn't known when the form ACTION attribute is populated - but can anyone confirm?
Here are my routes.
public static void RegisterRoutes( RouteCollection routes )
{
routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" );
routes.MapRoute(
String.Empty,
"{location}",
new {
controller = "Dashboard",
action = "Index",
id = ""
}
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
);
}
Here is the controller.
public class DashboardController : Controller
{
[HttpGet]
public ViewResult Index(string location)
{
return View(new AccItemSearch { Location = location });
}
}
Here is the form.
#using (Html.BeginForm("Index", "Dashboard", FormMethod.Get)) {
<h2>Where are you going?</h2>
<input type="text" placeholder="Area, town or postcode" id="location" name="location"/>
<button>Search!</button>
</div>
}
To clarify: the problem I want help with is how to have the user submit the form then land on a page with the URL: http://www.mydomain.com/searchterm and thus match the route, rather than on a page that with the URL http://www.mydomain.com/Dashboard
You will not be able to change the action attribute of the form during HTML generation (i.e. server side) as you simply don't know what it should point to. So if you need the URL to end up being the exact search term the easiest bet is probably to change the action attribute to it with JavaScript before the form is submitted, and have a controller that catches all urls that follow the www.domain.com/searchterm pattern.
You can't really redirect to a specific action because then that would become the URL returned to the browser, and I doubt you want one action per search term.
HTML:
<form method="post" id="myform">
<input type="text" id="searchterm" />
<input type="submit" value="Search" />
</form>
jQuery:
$(function () {
$("#myform").submit(function () {
var searchVal = $("#searchterm").val();
$(this).attr("action", searchVal);
});
});
Route:
routes.MapRoute(
"",
"{searchterm}",
new { controller = "Home", action = "Search" }
);
Note that this has to be put before the default route(s).
Action:
public ActionResult Search(string searchterm)
{
//do stuff
}
Now if a visitor enters the term "Alaska" and submits the search form, they will end up on domain.com/Alaska.
That form should be a POST to submit the form data.
The search should be a submit button
<input type="submit" name="Search" value="Search" />
Otherwise it looks good, unless you have a conflicting route. Tested your route in isolation and it seems fine. It's just that location is not being sent.

Resources