views:

208

answers:

3

There are tons of examples for model binding in html forms, but I'm wondering if its possible to, and if so how to, use model binding for ActionLinks/GET requests.

So, given the following model

public class Lurl
{
  public string Str {get;set;}
  public char Chr {get;set;}
  public double Dbl {get;set;}
}

and the following route (I'm not sure how this would be formed; I present it to show how I'd like the URL presents the properties Str, Chr and Dbl)

routes.MapRoute(
    "LurlRoute",
    "Main/Index/{str}/{chr}/{dbl}",
    new
    {
        controller = "Main",
        action = "Index",
        lurl = (Lurl)null
    }
);

I'd like to use it this way in my Controller

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(Lurl lurl)
{
  /* snip */
}

and this way in my page (two possible options; are there more?)

<div class="links">
  <%Html.ActionLink("Link one", "Index", new { lurl = Model })%><br />
  <%Html.ActionLink("Link two", "Index", 
         new { str = Model.Str, chr = Model.Chr, dbl = Model.Dbl })%>
</div>

Is this possible with the model binding infrastructure? And if so, what needs to be done to my samples to get them working?

+4  A: 

I think you'll have to pick either the class as a parameter approach

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(Lurl lurl)
{
   /* snip */
}

or the properties as parameters approach

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(string str, char chr, double dbl)
{
    /* snip */
}

...though in the class as a parameter approach, you can use the "UpdateModel" method. You can pass in a whitelist of parameters you want to update with that method just in case you only want to update a few values in your model.

Also, In your MapRoute, what parameter will lurl map to in your route path? I'm pretty sure there has to be a one to one correlation there.

Nick DeVore
+3  A: 

You can also use a custom model binder. Also read this.

Andrei Rinea
Also +1 for a great question!
Andrei Rinea
A: 

That doesn't work you can't send objects by GET. You have to send the object's property values as parameters and reinitialize your object in your action method. Take a look at Nick's example.

Jürgen