ASP.NET MVC Search Results Page MapRoute Doesn't Work - asp.net-mvc

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.

Related

HTTP POST fails when view has default name (route config)

The post of a view fails. It seems like the action name is missed.
If I change the POST action name in both controller and view to another arbitrary name, it works.
Controller
public class AuthenticationController : Controller
{
// GET: Authentication
[HttpGet]
public ActionResult Index()
{
var model = new IndexViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(IndexViewModel model)
{
if (ModelState.IsValid)
{
if(Membership.ValidateUser(model.Username, model.Password))
{
return RedirectToAction("Index", "Default");
}
else
{
model.ErrorMessage = "Failed to login. Please try again!";
}
}
return View(model);
}
}
View
#model Test.Web.Models.Authentication.IndexViewModel
#{
ViewBag.Title = "Log In";
}
<h2>Enter credentials to log on</h2>
#using (Html.BeginForm("Index", "Authentication"))
{
<p>
#Html.LabelFor(x => x.Username)<br />
#Html.TextBoxFor(x => x.Username)
</p>
<p>
#Html.LabelFor(x => x.Password)<br />
#Html.TextBoxFor(x => x.Password)
</p>
<input type="submit" value="Log In" />
}
I'm pretty sure the reason is the RouteConfig and the default action name.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
One solution is of course to rename both the GET and POST action, and not use Index, but is there a way of getting this to work as it is? Without any hack, that is.

BeginForm Always calling Index when submitting

I'm using MVC BeginForm to submit form data to my ActionMethod in Controller. The problem is that when every I click on submit button it keeps calling Index method instead of Actual method defined in BeginForm.
Here is my View
#model HRMS.DBModel.department
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("save", "Department", FormMethod.Post))
{
#Html.TextAreaFor(model => model.Name, new { #class = "form-control" })
<input type="submit" value="submit" />
}
and here is the Department Controller
public class DepartmentController : Controller
{
// GET: Department
public ActionResult Index()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult save()
{
return View();
}
}
and RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Location", action = "Index", id = UrlParameter.Optional }
);
}
I searched on google even found solutions but still my problem is still there.
Any help will be appreciated.
Thanks
Issue Resolved there was a form tag inside my Master page due to which it was calling Index Method, I removed that form tag and now its working fine

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" />
}

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

Resources