首页 > 解决方案 > 我有一个带有三个表单标签的视图。如何在控制器中分别处理每个表单?

问题描述

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

标签: asp.netasp.net-coremodel-view-controller

解决方案


假设我们有 3models

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

然后我们在 a 中有一个三个形式view。并且每个form对应于您在参数中ActionMethod指定的它们自己的firstHtml.BeginForm

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

推荐阅读