【问题标题】:How to pass Formcollection and Model value at the same time from view to controller?如何将 Formcollection 和 Model 值同时从视图传递到控制器?
【发布时间】:2015-06-09 19:43:15
【问题描述】:

我的 cshtml 页面有这样的代码

model Kouponer.Models.person_T  
@using (Html.BeginForm("BuynowForm", "Home"))
{    
    <label>@Model.name</label>
    <label>address</label>
    @Html.TextBox("address")<div>
    <input type="submit" value="Submit" class="btn btn-primary" />
}

而我目前的actionresult方法是

[HttpPost]
public ActionResult BuynowForm(FormCollection col)
{  string address = col["address"];
        return View();
}

在这里,我将只获得 formcollection 值。如何传递模型 表单集合?

【问题讨论】:

  • Please read this link 基本上,你不应该使用 FormCollection
  • @br4d,请解释一下为什么永远不要使用 FormCollection?是否存在性能问题或其他问题?
  • @br4d,感谢您的信息
  • @br4d 有一次我喜欢使用 FormCollection。当我想要一个 Get 和 Post 方法,但我不需要任何参数时......将 FormCollection 作为 post 的参数可以解决该问题。当然,在这种情况下,我实际上并没有使用它......它只是为了确保我不会因为具有重复的方法签名而出现编译错误。

标签: asp.net-mvc asp.net-mvc-5


【解决方案1】:

System.Web.Mvc 命名空间的Controller 类中有一个名为RequestHttpRequestBase 属性,其中包含当前http 请求的所有数据。在它的属性中,有一个名为FormNameValueCollection 属性,您正在寻找它。

用法是这样的:

[HttpPost]
public ActionResult BuynowForm(person_T model)
{
    string addressFromModel = model.Address;
    string addressFromRequest = Request.Form["address"];
    return View();
}

【讨论】:

  • @mamodom 现在我在 addressFromRequest 中获得了价值。我需要在 actionresult 中获取该 的值。但它的价值并没有得到。我们有什么需要改变的吗? ——
  • 请问您为什么要从NameValueCollection 中获取这些值,而不是从person_T 对象中获取这些值?
  • 我在使用 @Html.TextBoxFor(model => model.name, new { @class= "hidden" }) 时得到它
【解决方案2】:

除非我完全遗漏了某些东西,否则您应该能够在控制器的 sig 上添加模型类型。

[HttpPost]
public ActionResult BuynowForm(Models.person_T model, FormCollection col)
{  string address = col["address"];
   string addressFromModel = model.Address;
   return View();
}

但是,如果要使用模型绑定,则需要 FormCollection 对象似乎是多余的。我会阅读 cmets 中给出的链接,然后使用模型绑定。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多