Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's what you want to do, first define your route map:</p> <pre><code>routes.MapRoute( "Users", "{username}", new { controller = "User", action="index", username=""}); </code></pre> <p>What this allows you to do is to setup the following convention:</p> <ul> <li>Controller: User (the UserController type)</li> <li>Action: Index (this is mapped to the Index method of UserController)</li> <li>Username: This is the parameter for the Index method</li> </ul> <p>So when you request the url <strong>http://mydomain.com/javier</strong> this will be translated to the call for <strong>UserController.Index(string username)</strong> where <strong>username</strong> is set to the value of <em>javier</em>.</p> <p>Now since you're planning on using the MembershipProvider classes, you want to something more like this:</p> <pre><code> public ActionResult Index(MembershipUser usr) { ViewData["Welcome"] = "Viewing " + usr.UserName; return View(); } </code></pre> <p>In order to do this, you will need to use a ModelBinder to do the work of, well, binding from a username to a MembershipUser type. To do this, you will need to create your own ModelBinder type and apply it to the user parameter of the Index method. Your class can look something like this:</p> <pre><code>public class UserBinder : IModelBinder { public ModelBinderResult BindModel(ModelBindingContext bindingContext) { var request = bindingContext.HttpContext.Request; var username = request["username"]; MembershipUser user = Membership.GetUser(username); return new ModelBinderResult(user); } } </code></pre> <p>This allows you to change the declaration of the Index method to be:</p> <pre><code>public ActionResult Index([ModelBinder(typeof(UserBinder))] MembershipUser usr) { ViewData["Welcome"] = "Viewing " + usr.Username; return View(); } </code></pre> <p>As you can see, we've applied the <strong>[ModelBinder(typeof(UserBinder))]</strong> attribute to the method's parameter. This means that before your method is called the logic of your <strong>UserBinder</strong> type will be called so by the time the method gets called you will have a valid instance of your MembershipUser type.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload