user1228
user1228

Reputation:

Model binding and GET requests?

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?

Upvotes: 10

Views: 2854

Answers (2)

Andrei R&#238;nea
Andrei R&#238;nea

Reputation: 20780

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

Upvotes: 3

Nick DeVore
Nick DeVore

Reputation: 10166

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.

Upvotes: 5

Related Questions