views:

273

answers:

2

I am trying to build a small ASP.NET MVC 2 application.I have a controller class with the below method in it

  public ActionResult Index()
    {
        TestMvc.Models.PersonalInformation objPerson = new TestMvc.Models.PersonalInformation();
        objPerson.FirstName = "Shyju";
        objPerson.LastName = "K";
        objPerson.EmailId="[email protected]";
        return View(objPerson);
    }

And when the page (View) being called, i can see this data there as my view has these data's displaying. Now i want to know how can i pass a query string in the url and use that id to build the PersonalInformation object.Hoe can i read the querystring value ? Where to read ?

I want the quesrtstring to be like http://www.sitename/user/4234 where 4234 is the user id

+3  A: 

http://www.sitename/user/4234 is not a querystring. The querystring is the part of the URL that comes after the ?, as in http://www.sitename/user?userId=42

However, the default routes that come with the MVC project template should allow you to simply change the signature of your action method to

public ActionResult Index(int id)

and you should get the desired result. You should look into how routing works in MVC if you want full control of your URLs.

Also, note that the index action is usually used for showing a list of all objects, so you probably want the Details action for showing 1 user object.

Jonas H
@Shyju: at Jonas sample 4234 can be obtained by using RouteData.Values["Id"]
Junior Mayhé
A: 

What you want is to modify your action to accept an id like so:

public ActionResult Index(string id)
{
  TestMvc.Models.PersonalInformation objPerson = new TestMvc.Models.PersonalInformation();
  if (!string.isNullOrEmpty(id))
  {
    objPerson = getPerson(id);
  }

  return View(objPerson);
}

Then add a route to your global.asax:

routes.MapRoute(
  "MyRoute",                                              // Route name
  "user/{id}",                           // URL with parameters
  new { controller = "mycontroller", action = "index", id = ""}  // Parameter defaults
);
Bradley Mountford