【问题标题】:I have a View with three form tags. How do I go about processing each form separately in the controller?我有一个带有三个表单标签的视图。如何在控制器中分别处理每个表单?
【发布时间】:2020-08-14 18:09:39
【问题描述】:

我是 MVC 的新手,遇到了比我见过的大多数示例更复杂的表单的问题。 视图分为三个部分,实际上是表单。 我的问题是关于传递模型和处理这些表格。 我的一位同事建议为每个表单使用三个控制器。 但是,我如何将单独的模型传递给每个表单? 我想你应该已经明白了。 你能帮我完成这个任务吗?

【问题讨论】:

  • 请分享一些代码。
  • 我还没准备好分享代码,因为我认为这个问题太多了。明天我会努力做到这一点。现在我很高兴能得到一些解决这个问题的想法。
  • 您可以在一个view 中使用多个表单,但每个视图将对应于控制器中自己的ActionMethod
  • 如何将不同的模型传递给每个表单?
  • 不要将模型传递给表单。将input 元素的name 属性用作Model property name。当表单发布时,它将通过使用name 属性获得价值。

标签: asp.net asp.net-core model-view-controller


【解决方案1】:

假设我们有 3 个models

Public class Model1
{
    public string name{get;set;}
}
Public class Model2
{
    public string name{get;set;}
}
Public class Model3
{
    public string name{get;set;}
}

然后我们有一个view 中的三个表格。并且每个form 对应于您在Html.BeginFormfirst 参数中指定的自己的ActionMethod

@Html.BeginForm("Model1Action","ControllerName",FormMethod.Post)
{
    //dont use @Model.Name in the name property of input element.
    <input type="text" name="name"/>
}
@Html.BeginForm("Model12Action","ControllerName",FormMethod.Post)
{
    //dont use @Model.Name in the name property of input element.
    <input type="text" name="name"/>
}
@Html.BeginForm("Model3Action","ControllerName",FormMethod.Post)
{
    //dont use @Model.Name in the name property of input element.
    <input type="text" name="name"/>
}

然后在控制器的Action方法中

[HttpPost]
Public ActionResult Model1Action(Model1 obj)
{
    Response.Write(obj.name);
}
[HttpPost]
Public ActionResult Model1Action(Model1 obj)
{
    Response.Write(obj.name);
}
[HttpPost]
Public ActionResult Model1Action(Model1 obj)
{
    Response.Write(obj.name);
}

【讨论】:

  • @Html.BeginForm 在 asp.net core 中有点过时了
  • 在视图中,如何通过所有三个模型?
  • 同样在 Action 方法中,你如何返回 View - return View(obj) 将只使用一个模型?
  • @EisKarlsson 不要创建HttpGetHttpGet 方法,仅使用HttpPost 方法。
猜你喜欢
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
相关资源
最近更新 更多