Display query string in specific format in mvc form - asp.net-mvc

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
}

Related

Action link to absolute url (remove the ?) and keep the parameter

i'm trying to get an absolute url after sending a parameters from action link and I need it to be like
http://MySite/Controller/View/CityName
so I will be able to preform a search on the results page and no losing the first parameter (e.g.)
http://MySite/Controller/View/NewYork?Lecture=bobdillen
code :
#foreach (var city in #ViewBag.City)
{
#Html.ActionLink((string)#city, "LectureIn", new { #city }, null)
}
the action(LectureIn) code :
#using (Html.BeginForm("Search", "Lecture"))
{
<div class="form-group">
<div id="searchLecture" class="input-group">
#Html.TextBoxFor(m => m.SearchTerm, new { #class = "form-control", placeholder = "" })
<span class="input-group-addon">
<button type="submit"> <i class="glyphicon glyphicon-search"></i></button>
</span>
</div>
</div>
}
and in the controller :
public ActionResult LectureIn(string search = null)
{
// Do Staf
return View();
}
I have tried to change the routes but it didn't change
routes.MapRoute(
"lectureIn",
"{controller}/{action}/{id}",
new { controller = "TMaps", action = "lectureIn", City = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

MVC - Ajax.BeginForm() generating empty action

Current page URL: http://localhost:25265/SearchResultsList.aspx
view looks like:
#using (Html.BeginForm("RefineSearchResults", "Search", FormMethod.Post, new {id = "myForm"}))
{
<input type="submit" value="submit" />
}
Routes:
routes.MapRoute(
"Search",
"SearchResultsList.aspx",
new { controller = "Search", action = "SearchResults" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index"},
namespaces: new[] { "MyApp.WebUI.Controllers" }
);
But, I noticed that it's generating empty action.
looks like:
<form action method="post">
<input type="submit" value="submit"> </form>
Can anyone please tell me what's this happening? Where I'm doing wrong!!

Customizing Routes in ASP.NET MVC4

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
});

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.

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

Resources