Reputation: 3654
I'm quite new to ASP.NET and C# and I'm having some issues with my routing. Was hoping someone would be so kind to help me out.
A user is supposed to give 3 parameters (string
, bool
, bool
).
So I have a small form on my index page:
<% using (Html.BeginForm("search", "Home")) { %>
<label >Name: </label><br />
<input type="text" id='ml' name='ml' /><br />
<label >Sort members alphabethic? </label> <input type="checkbox" id='sortalph' name='sortalph' /><br />
<label >Number the list? </label><input type="checkbox" id='number' name='number' /><br />
<input type="submit" value='Submit'/>
<% } %>
Global.asax.cs
is set up like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index"} // Parameter defaults
);
routes.MapRoute(
"Search", // Route name
"{controller}/{action}/{ml}/{sortalph}/{number}", // URL with parameters
new { controller = "Docent", action = "Search" } // Parameter defaults
);
The start of the Search
method in my HomeController
looks like this:
public ActionResult Search(string ml, bool? sortalph, bool? number)
{
if (sortalph == null)
{
sortalph = false;
}
if (number == null)
{
number = false;
}
When I debug sortalph
and number
are always null
. I'm not sure why.
Upvotes: 1
Views: 149
Reputation: 7448
The problem is strictly related to two factors:
bool
and not bool?
value="true"
so when they are checked, the correct value will be sent and the property will get the right value.Apart from that, you could use html helper methods instead of plain html to create your form. Your html has many flaws, like labels missing the for
attribute, etc.
Also since it's a search form, you should use an HTTP GET method to make the search result indexable and bookmarkable, but you're not specifing it and the default overload of BeginForm
will render a form tag using HTTP POST method.
Upvotes: 1
Reputation: 42333
You don't need to add a special route for these since they are simply going to be added by the browser into the query string, or into the post body if the form is a post, when the form is submitted.
So, if the browser does a GET, then it actually forms the url /home/search?ml=[whatever]&sortalph=[whatever]&number=[whatever]
. MVC automatically maps the parameters, by name, to those values from the query string.
If you comment out the route you should find that it will all start working.
Upvotes: 1