首页 > 解决方案 > 一个视图上的 GET 和 POST 方法

问题描述

我想知道是否可以在同一个视图/表单上使用 GET 和 POST 方法,或者它们应该在两个视图上分开?另外,我可以在一个视图上有两个模型(IEnumerable,,Generic...)吗?

控制器

public class MyController : Controller
   {

     public ActionResult GetView()
      {
          return View();
      }


        [HttpGet]
        public ActionResult PostView()
        {

            return View();
        }


        [HttpPost]
        public ActionResult PostView()
        {
                        return View();
        }
    }

看法

@model IEnumerable<AppName.Models.OneClass>
@using AppName.Models


@using (Html.BeginForm("GetView", "MyController", FormMethod.Get))
{some code}

@using (Html.BeginForm("PostView", "MyController", FormMethod.Post))
{some code}

这可能吗?

标签: asp.netasp.net-mvc

解决方案


您可以在一个视图上拥有多个表单,是的。

单独的模型,你也可以这样做。

想象一下,您有 Model1 和 Model2,并且您想将它们分别用于不同的形式。

您创建第三个包装模型 Model3,其中 Model1 和 2 成为简单的属性,然后将每个模型用于自己的表单/局部视图,无论如何。

您的模型将如下所示:

public class WrapperModel {
    public Form1Model model1 { get; set; }
    public Form2Model model2 { get; set; }
}

那么您的表格 1 使用 WrapperModel.model1 而另一个使用第二个模型。当你有这样的场景时,这很常见。

例如,您可以为表单使用一些局部视图,并在每个视图中指定不同的模型。这至少可以让它们之间有一些分离。


推荐阅读