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.
Related
I am certain this question has been asked before and this is NOT my only form in this project, but for some reason I cannot get my Form.Post to work when the "submit" button is pressed on this particular form. Any assistance will be greatly appreciated.
Note: I checked the model Contract and there are no [Required Fields]. Also, I did get it to post back using $.ajax POST {}, which I may need to resort to
Here is the frame for the Form
#using (Html.BeginForm("Add_Contract", "Contract", FormMethod.Post, new { #id = "contractForm", role="form" }))
{
<div class=content>
... Content goes here
</div>
<input type="submit" value="Save Contract" />
}
Here is my Controller:
// Add a Contract
public ActionResult Add_Contract()
{
var returned = new Contract();
return View(returned);
}
[HttpPost]
public ActionResult Add_Contract(Contract data)
{
return View(data);
}
Here is my route.config
public class RouteConfig
{
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 }
);
}
}
So, as I dug deeper into this issue, I figured out the issue was that I did not have any front-end validation on the data I was inputting yet, and even though I did not have any required fields in the model, I was inputting characters in a field that was set up as an integer. I discovered the issue when I created a dummy view and let the system create the scaffolding and when I tried to enter the same character data in that int field, an error popped up stating that the field must be integer. Once I added an integer in the text box, the post worked. Thanks for anyone who reviewed this post.
I am trying to link inside the same folder, I have the following structure
/Home/Index
/Home/About
/Home/Contact
When I start the webpage, I link to the Index, so I get the webpage on the screen: www.example.com.
Now I would like to link to another page so I get: www.example.com/Contact.html (or even better I would like to get www.example.com/Contact) however I get www.example.com/Home/Contact.
I use this as an action link:
<li class="pure-menu-item pure-menu-selected">#Html.ActionLink("Contact us", "Contact", "Home")</li>
This is my route:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
What could I change to get the desired result?
Decorate you Contact action with a RouteAttribute and pass it the desired route as parameter (i.e. "Contact")
Edit
Here's an example HomeController using the RouteAttribute:
public class HomeController
: Controller
{
public IActionResult Home()
{
return this.View();
}
[Route("Contact")]
public IActionResult Contact()
{
return this.View();
}
}
Note that you can use the RouteAttribute on Controllers, too. For instance, if I added a Route("Test") attribute on the HomeController, all of my controllers actions would look like: "/Test/[ActionRoute]".
In your views, you can use the following syntax, instead of using the old #Html.ActionLink tag helper:
<li class="pure-menu-item pure-menu-selected">
<a asp-controller="Home" asp-action="Contact">Contact Us</a>
</li>
In my opinion, those attribute tag helpers are way cleaner and html friendly ;)
i was able to fix it with some good reading and searching and this is what i came up with:
i added this to the routeConfig for each link to a html page:
routes.MapRoute("Index", "Index", new { controller = "Home", action = "Index" });
routes.MapRoute("About", "About", new { controller = "Home", action = "About" });
routes.MapRoute("Contact", "Contact", new { controller = "Home", action = "Contact" });
and instead of using an action link i use a route link:
<li class="pure-menu-item">#Html.RouteLink("About us", "About")</li>
this gives the desired result: www.example.com/About
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
});
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.
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.