【问题标题】:How to bind model during an action?如何在动作期间绑定模型?
【发布时间】:2015-08-03 20:31:45
【问题描述】:

我有一个动态 url 处理器

public ActionResult DynamicUrl(string slug = null)

此方法通过 slug 工作(顺便说一句,slug 代表什么?)并确定 slug 是显示产品还是执行产品搜索。

作为产品搜索的一部分,我有一个 page=1 查询字符串参数。

E.g. /Womens/Dresses?page=2

通常我会在将页面查询字符串绑定到 ProductSearch 模型的普通产品搜索操作中执行此操作。

public ActionResult Results(ProductSearchModel  searchModel)

如何在操作过程中绑定查询字符串?例如

public ActionResult DynamicUrl(string slug = null)
{
    ProductSearchModel psm = new ProductSearchModel();

    //Auto bind psm here.
    // E.g. Controller.BindModel(psm);
}

希望我不会偏离正轨。

【问题讨论】:

  • slug 是一个人类可读的、友好的 url 部分,通常附加在 url 的末尾。如果您在地址栏中仅输入http://stackoverflow.com/questions/30386176,请注意在呈现页面时它是如何将/how-to-bind-model-during-an-action 附加到末尾的
  • stackoverflow.com/questions/6055415/… 这是您要找的东西吗?
  • 如果你有一个查询字符串?page=2,那么该方法应该有一个匹配的参数——public ActionResult DynamicUrl(string slug, int page)`(不需要有string slug = null,因为string是引用类型)
  • 以上所有 cmets 都与我询问的主题不同。
  • 为什么你不想使用 Request.QueryString ?

标签: c# asp.net-mvc asp.net-mvc-5 model-binding


【解决方案1】:

你的意思是:

UpdateModel(psm);

这会将当前表单集合绑定到指定的模型。

你也可以使用:

TryUpdateModel(psm);

如果发生故障并返回truefalse,此版本不会抛出异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-20
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多