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

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

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

MVC Area - How to Link to Root folder in BeginForm

I need to define a link to LogOff controller which is in my Root shared folder; within BeginForm tag.
#using Microsoft.AspNet.Identity
#if (Request.IsAuthenticated) {
using (Html.BeginForm("", "", FormMethod.Post, new { id = "logoutForm", action = "Account/LogOff"}))
{
#Html.AntiForgeryToken()
#Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
#: | Log off
}
}
else {
#Html.ActionLink("Register", "Register", "Account")
#: |
#Html.ActionLink("Login", "Login", "Account")
}
Above works fine if I'm in root folder. But if clicked from Areas, it gives me The resource cannot be found error.
Requested URL: /MyApp/Area/Account/LogOff
The correct link should be /MyApp/Account/LogOff
I saw examples using #HTML.ActionLink but would prefer to keep define it in BeginForm, so the URL is not revealed to user.
I solved the problem with the following code.
First I mapped a route as follows
//Route config for logging off from areas.
routes.MapRoute(
name: "LogOff",
url: "Account/LogOff/",
defaults: new { controller = "Account", action = "LogOff" }
);
Then calling the route to logout, I used the following
#using (Html.BeginRouteForm("LogOff", FormMethod.Post, new { id = "logoutForm" })) {
#Html.AntiForgeryToken()
Log off
}
It may be easier to just add the Area routevalue to the BeginForm parameters. Leave it blank to point it to the root area, like this: new { Area = "" }
using (Html.BeginForm("LogOff", "Account", new { Area = "" }, FormMethod.Post, new { id = "logoutForm", #class = "navbar-right" }))
{
#Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>Log off</li>
</ul>
}
This is using MVC 5

ASP.NET MVC ajax - data transfer

How can I get result from action?
I need to show the commentID on the page (aspx) after successes comment insert.
controller
[AcceptVerbs(HttpVerbs.Post )]
public ActionResult ShowArticleByAjax(Guid id, string commentBody)
{
Guid commentID = Comment.InsertComment(id, commentBody);
//How can I tranfer commentID to the aspx page ???
return PartialView("CommentDetails",Article.GetArticleByID(id));
}
ascx
<%using (Ajax.BeginForm("ShowArticleByAjax", new { id = Model.ID },
new AjaxOptions {
HttpMethod = "Post",
UpdateTargetId = "divCommentDetails",
OnSuccess = "successAddComment",
OnFailure = "failureAddComment",
OnBegin = "beginAddComment"
}))
{ %>
<p>
<%=Html.TextArea("commentBody", new { cols = "100%", rows = "10" })%>
</p>
<p>
<input name="submit" type="image" src="../../Content/Images/Design/button_s.gif"
id="submit" />
</p>
<%} %>
aspx
doesn't matter
Use the this:
ViewData["ID"] = commentID;
and then print it with:
<%= ViewData["ID"]%>

Resources