views:

76

answers:

1

Say I want to display user details like so: http://www.mysite.com/user/1

I set a route up like so:

routes.MapRoute("UserDetails", "user/"{id}",
    new { controller = "User", action = "Details" });

Then my controller:

public ActionResult Details(int id)
{
    User currentUser = _userRepository.GetUser(id);
    if (currentUser == null) return View("NotFound");
    return View(currentUser);
}

So far so good. Everything works like I expect. Now I also want a form where one can enter the ID to look up then click Submit to get the same result. eg:

<% Html.BeginForm("Details","User",FormMethod.Post); %>
<input type="text" value="" name="id" id="userid" />
<%= Html.Button("Search For User","submit","searchforuser"; %>
<% Html.EndForm(); %>

This is where I'm currently lost. I don't want to just have [AcceptVerbs(HttpVerbs.Post)] and use a RedirectToAction if possible. I just want to take whatever number they input - say 38 - and go to www.mysite.com/user/38

Is this even possible with straight MVC? I'm sure there are jQuery-related ways but so far have had no luck getting anything beyond a basic jQuery alert working so don't really want to waste any more time on it for now.

+1  A: 

MVC will automatically match by name query parameters (for GET) or form input files (for POST) to the action parameters by name. Unfortunately, your id does not match the action parameter name, so MVC can't match them. To fix this, you can:

  • change the id on the <input type="text" value="" name="id" id="userid" /> from userid to id
  • change the parameter name of the Details action from id to userid (and don't forget to update your route as well)

I just confirmed that at least the first one fixes the issue on MVC2 RC. I don't have MVC1, so I can't check if it works there as well, but as far as I know there are no major differences in how MVC1 and MVC2 match parameters.

Franci Penov
Since you're the only one who bothered replying, I see no choice other than to accept your answer :)
FerretallicA
You don't have to accept my answer if it doesn't work for you. Even if it's the only answer you got. :-)
Franci Penov