开发者

ASP.NET MVC 2.0: How to read querystring value

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="shyju@company.com";
        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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜