模型绑定和GET请求?

时间:2009-04-20 15:16:34

标签: asp.net-mvc model-binding http-get

在html表单中有大量的模型绑定示例,但我想知道它是否可能,如果是这样,如何使用ActionLinks / GET请求的模型绑定。

所以,给出以下模型

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

以及以下路线(我不确定这将如何形成;我提出它以显示我希望URL如何呈现属性Str,Chr和Dbl)

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

我想在我的Controller中以这种方式使用它

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

这种方式在我的页面中(两种可能的选项;还有更多吗?)

<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>

模型绑定基础设施是否可以实现?如果是这样,我的样品需要做些什么才能使它们起作用?

2 个答案:

答案 0 :(得分:5)

我认为您必须选择该类作为参数方法

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

或作为参数的属性接近

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

...虽然在类中作为参数方法,但您可以使用“UpdateModel”方法。您可以使用该方法传入要更新的参数白名单,以防您只想更新模型中的一些值。

此外,在您的MapRoute中,哪些参数将在您的路径路径中显示?我很确定那里必须有一对一的关联。

答案 1 :(得分:3)

您还可以使用custom model binder。另请阅读this