Action link to absolute url (remove the ?) and keep the parameter - asp.net-mvc

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

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 to make custom URL with custom routing in MVC

I have problem to make custom url in mvc. I want to make url like this one:
http://www.domainname.com/directory/bysearch/value1/value2
but its make like this
http://www.domainname.com/directory/bysearch?txtaddress=value1&searchString=value2
and
RouteConfig.cs code
routes.MapRoute(
name: "Directory",
url: "Directory/{qualifier}/{v1}/{v2}/{v3}/{v4}/{v5}/{v6}/{v7}/{v8}",
defaults: new
{
controller = "Directory",
action = "index",
qualifier = UrlParameter.Optional,
v1 = UrlParameter.Optional,
v2 = UrlParameter.Optional,
v3 = UrlParameter.Optional,
v4 = UrlParameter.Optional,
v5 = UrlParameter.Optional,
v6 = UrlParameter.Optional,
v7 = UrlParameter.Optional,
v8 = UrlParameter.Optional
});
routes.MapRoute(
name: "DirectorySerach",
url: "Directory/bysearch/{v1}/{v2}",
defaults: new
{
controller = "Directory",
action = "Search",
v1 = UrlParameter.Optional,
v2 = UrlParameter.Optional
});
Controller
public ActionResult Index(string qualifier, string v1, string v2, string v3, string v4, string v5, string v6, string searchString, int page = 1)
{
// code logic here
return View();
}
public ActionResult Search(string v1 = null,string v2 = null)
{
//code logic here
return View();
}
View
#using (Html.BeginForm("search","Directory", FormMethod.Get))
{
<div class="form-group">
<div class="c-checkbox">
<input id="chkOnline" name="chkOnline" class="c-check" type="checkbox">
<label for="chkOnline" class="c-font-thin c-font-17">
<span></span>
<span class="box"></span> Online
<span class="check"></span>
</label>
</div>
</div>
<div class="form-group">
#Html.TextBox("txtaddress", null, new { #class = "form-control c-square c-theme input-lg", #placeholder = "Address OR ZIP/Postal Code OR City" })
</div>
<div class="input-group input-group-lg c-square">
#Html.TextBox("searchString", null, new { #class = "form-control c-square c-theme input-lg", #placeholder = "Enter Keyword" })
<span class="input-group-btn">
<button class="btn c-theme-btn c-btn-square c-btn-uppercase c-font-bold" type="submit">Go!</button>
</span>
</div>
}
please help/guide me, where i am wrong or what is the problem. and how to resolve.
i appreciate your value able time and effort. thanks in advance.
If you want to make clean URl then you need to craete URl manually, As Form Submit will always create query string.
So remove your form and replace button with hyperlink. and write click event on link.
#Html.TextBox("v1", null, new { })
#Html.TextBox("v2", null, new { })
GO
Now Write a function which will create URl
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
$('#btnSearch').on('click',function(){
var baseUrl = '#Url.Action("Search", "Directory")';
var gettext1= $('#v1').val();
var gettext2= $('#v2').val();
if(gettext1){
baseUrl += '/'+gettext1;
}else{
baseUrl += "/0";
}
if(gettext2){
baseUrl +="/"+ gettext2;
}else{
baseUrl += "/0";
}
location.href=baseUrl;
});
});
</script>
here you need to handle 0. as if user doesn't enter anything in textbox then I'm passing 0.

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

how do I map my text box string into my url route?

I have a text box that I enter data into and pass with a post to my 'home' controller on action 'results'
I want the url to end up looking like this when I post back
https://localhost:44301/Home/Results/San Francisco, CA, United States
I'm passing the text box data like this.
#using (Html.BeginForm("Results", "Home", FormMethod.Get, new { #class = "navbar-form navbar-left", role = "search" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="navbarautocomplete" name="location">
<button type="submit" class="btn btn-default">Submit</button>
</div>
}
Here is my routing.
routes.MapRoute("SearchResults",
"home/results/{location}",
new { controller = "Home", action = "Results", location = ""}
);
How do I set my routing or my form to see the data that has been submitted as location in my url?
I can get it to look like this.
https://localhost:44301/home/results?location=San+Francisco%2C+CA%2C+United+States
but I want san francisco after /results/
As #StephenMuecke mentions in the comments, you could POST your search value to a (separate) action, then redirect to your results page, passing the location as a parameter:
#using (Html.BeginForm("Search", "Home", FormMethod.Post, new { #class = "navbar-form navbar-left", role = "search" }))
{
<div class="form-group">
<input type="text" class="form-control" placeholder="Search" id="navbarautocomplete" name="location">
<button type="submit" class="btn btn-default">Submit</button>
</div>
}
Then in your controller:
[HttpPost]
public ActionResult Search(string location)
{
return RedirectToAction("Results", new { location = location });
}
public ActionResult Results(string location)
{
return Content("location is: " + location);
}
You'll also to have the following route set up in your RouteConfig to get the friendly URL (make sure this is above the default route, as they match top-down).
routes.MapRoute(
name: "SearchResults",
url: "Home/Results/{location}",
defaults: new { controller = "Home", action = "Results" }
);

ASP MVC url/link generation on Area produces empty

I am using ASP MVC 5 and trying to generate a link in my view inside the "ControlPanel" Area
my view rootfolder/Areas/ControlPanel/Views/CourseCategory/Index.cshtml
#Html.ActionLink("edit", "Edit", new { id = item.Id }, new { #class = "btn btn-default btn-xs" })
#Html.ActionLink("delete", "Delete", new { id = item.Id }, new { #class = "btn btn-danger btn-xs" })
my AreaRegistration
public class ControlPanelAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "ControlPanel";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.Routes.LowercaseUrls = true;
context.MapRoute(
name: "ControlPanel.CourseCategory",
url: "controlpanel/course-categories/{id}",
defaults: new { controller = "CourseCategory", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Website.Areas.ControlPanel.Controllers" }
);
}
}
RouteConfig file
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "HomePage",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
}
}
my controller
namespace Website.Areas.ControlPanel.Controllers
{
public class CourseCategoryController : ControlPanelController
{
public CourseCategoryController(IUnitOfWork uow)
:base(uow)
{
}
public ActionResult Index()
{
return View(_uow.Repository<CourseCategory>().GetAllOrderByCode());
}
}
}
now the output html produces empty href
<a class="btn btn-default btn-xs" href="">edit</a>
<a class="btn btn-danger btn-xs" href="">delete</a>
what is the correct way of generating link on Html.ActionLink or Url.Action and Url.RouteUrl in this case?
It looks like you are missing the controller in your route values (I noticed you are not specifying one anywhere in your #Html.ActionLink)
#Html.ActionLink("edit", "Edit", new { controller="CourseCategory", id = item.Id }, new { #class = "btn btn-default btn-xs" })
Or - an alternative overload of the Html.ActionLink
#Html.ActionLink("edit", "Edit", "CourseCategory", new { id = item.Id }, new { #class = "btn btn-default btn-xs" })
Lastly, it never hurts to include the area name as part of the RouteValues dictionary, but this is not required.
EDIT
It looks like you updated your question with some additional information. This does not look right (having a blank value for URL)
routes.MapRoute(
name: "HomePage",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
By default, it should look something like this
routes.MapRoute(
name: "HomePage",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
I would assume having a blank URL is definitely something that could cause a blank URL to be created in an Html.ActionLink. These helpers looks at your route config to generate the URL and this one seems to be taking over probably everything since it matches everything.
Try to do this area name along with id
#Html.ActionLink("edit", "Edit", new { id = item.Id, area = "ControlPanel" }, new { #class = "btn btn-default btn-xs" })
#Html.ActionLink("delete", "Delete", new { id = item.Id, area = "ControlPanel" }, new { #class = "btn btn-danger btn-xs" })
I think the problem is with the defaults which points to the Index action and action is not bound on the route!??

Resources