How to convert model into url properly in asp.net MVC?
Posted
by 4eburek
on Stack Overflow
See other posts from Stack Overflow
or by 4eburek
Published on 2010-06-17T12:01:42Z
Indexed on
2010/06/17
12:03 UTC
Read the original article
Hit count: 283
From the SEO standpoint it is nice to see urls in format which explains what is located on a page
Let's have a look on such situation (it is just example)
We need to display page about some user and decided to have such url template for that page:
/user/{UserId}/{UserCountry}/{UserLogin}
.
And create for this purpose such model
public class UserUrlInfo{
public int UserId{get;set;}
public string UserCountry{get;set;}
public string UserLogin{get;set;}
}
I want to create controller method where I pass UserUrlInfo object but not all required fields. Classic controller method for url template shown above is following
public ActionResult Index(int UserId, string UserCountry, string UserLogin){
return View();
}
and we need to call it like that
Html.ActionLink<UserController>(x=>Index(user.UserId, user.UserCountry, user.UserLogin), "See user page")
I want to create such controller method
public ActionResult Index(UserUrlInfo userInfo){
return View();
}
and call it like that: Html.ActionLink<UserController>(x=>Index(user), "See user page")
Actually I works when we add one more route and point it to the same controller method, so routing will be:
/user/{userInfo}
/user/{UserId}/{UserCountry}/{UserLogin}
In this situation routing engine gets string method of our model (need to override it) and it works ALMOST always. But sometimes it fails and show url like
/page/?userInfo=/US/John
So my workaround does not always work properly. Does anybody know how to work with urls in such way?
© Stack Overflow or respective owner