10

在 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
    }
);

我想在我的控制器中以这种方式使用它

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

模型绑定基础设施可以做到这一点吗?如果是这样,需要对我的样品做些什么才能让它们发挥作用?

4

2 回答 2

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 中,lurl 将映射到您的路由路径中的哪个参数?我很确定那里必须存在一对一的相关性。

于 2009-04-20T21:55:54.920 回答
3

您还可以使用自定义模型绑定器。也读这个

于 2009-04-21T01:44:55.947 回答