【问题标题】:MVC3 binding querystring parameter to deep object propertyMVC3 将查询字符串参数绑定到深层对象属性
【发布时间】:2011-07-27 20:26:55
【问题描述】:

我的域设置类似于

public class Pagination 
{
    public int? Page { get; set; }
}

public class IndexViewModel
{
    public Pagination  Pagination  { get; set; }
}

public class HomeController : Controller
{ 
    public ActionResult Index(IndexViewModel model, Pagination pg, string page)
    {

        return View(model);
    }
}

当我导航到/?Page=5 时,我希望 5 是 model.Pagination.Page 的值也为 5,但似乎 MVC 不会绑定超过 1 层深度的查询参数。

我能做些什么来改变这种情况?

或者更改此设置比它的价值更麻烦?我应该这样做

public class HomeController : Controller
{ 
    public ActionResult Index(IndexViewModel model, Pagination pg, string page)
    {
       model.Pagination = pg;

        return View(model);
    }
}

*注意三重参数是为了说明它不会填充 IndexViewModel 但它会填充其他两个参数,因为它们的深度为 0 或 1 层。

【问题讨论】:

  • 查询参数不是/?Pagination.Page=5,那么为什么期望model.Pagination.Page会被设置呢?模型绑定器应该设置pg.Page(以及page),因为你现在有你的签名,但我认为你的期望是不正确的。
  • 因此我的问题是我该怎么做才能使它填充来自page=5的model.Pagination.page

标签: asp.net asp.net-mvc asp.net-mvc-3 modelbinders querystringparameter


【解决方案1】:

你的方法签名不应该是……

public ActionResult Index(int? page)
{
    var model = new IndexViewModel{
                        Pagination = new Pagination { Page = page ?? 1 } };
    if(page.HasValue)
        model.Stuff = StuffGenerator
                          .GetStuff()
                          .Skip(page.Value * _pageSize)
                          .Take(_pageSize);
    else
        model.Stuff = StuffGenerator.GetStuff().take(_pageSize);
    return View(model);
}

您的示例听起来像 GET,但看起来像 POST。

【讨论】:

  • 这是一个可以通过 PostRedirectGet 提供给模型的 get,模型保存在 tempdata 中。
  • @ChrisMarisic:为什么你的模型和方法签名都有分页实例?
  • 我不希望它两者兼有,我只希望模型拥有它但模型不会深度绑定值。我确实需要控制器和视图中的页面值。
  • @ChrisMarisic:我认为这是不可能的。 ModelBinding 仅发生在 POST 上。 MVC 不会解析 URL 并将您的模型绑定到其中的一部分。
  • @Will 也许我在某处使用了错误的术语,但 MVC 肯定会在获取请求时填充我的分页 pg 和字符串页面参数
猜你喜欢
  • 2012-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
相关资源
最近更新 更多