【问题标题】:MVC - GET & POST actions with the same name and parameters in the same controllerMVC - 在同一个控制器中具有相同名称和参数的 GET 和 POST 操作
【发布时间】:2014-02-17 22:37:44
【问题描述】:

我正在开发一个 MVC4 项目,我在同一个控制器中有两个具有相同名称和参数的操作:

public ActionResult Create(CreateBananaViewModel model)
{
    if (model == null)
        model = new CreateBananaViewModel();

    return View(model);
}

[HttpPost]
public ActionResult Create(CreateBananaViewModel model)
{
    // Model Save Code...

    return RedirectToAction("Index");
}

我想将现有模型传递给我的 Create 方法的原因是克隆然后修改现有模型。

显然编译器不喜欢这样,所以我改变了一种方法,看起来像这样:

[HttpPost]
public ActionResult Create(CreateBananaViewModel model, int? uselessInt)
{
    // Model Save Code...

    return RedirectToAction("Index");
}

这完全可以接受吗?或者有没有更好的方法来解决这个问题?

编辑/解决方案:

看起来我完全把情况复杂化了。这是我的解决方案

public ActionResult Duplicate(Guid id)
{
    var banana = GetBananaViewModel(id);

    return View("Create", model);
}

public ActionResult Create()
{
    var model = new CreateBananaViewModel();

    return View(model);
}

【问题讨论】:

  • 您还可以使用 ActionName 属性为 Create 和 Update 方法提供相同的签名

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


【解决方案1】:

您真的需要在 GET Create 操作中使用 model 参数吗?你可以这样做:

public ActionResult Create()
{
    var model = new CreateBananaViewModel();

    return View(model);
}

或者,如果您希望接收一些关于操作的查询数据 (www.mysite.com/banana/create?bananaType=yellow)

public ActionResult Create(string bananaType, string anotherQueryParam)
{
    var model = new CreateBananaViewModel()
    {
       Type = bananaType
    };
    return View(model);
}

让你的 POST 操作保持原样

[HttpPost]
public ActionResult Create(CreateBananaViewModel model) {}

【讨论】:

  • 你是 100% 正确的,我完全把情况复杂化了,忘记了 MVC 的一些基础知识。我现在将我的克隆操作设置为返回带有模型的创建视图,而不是重定向到创建方法并尝试发送模型。抱歉这个愚蠢的问题。
猜你喜欢
  • 1970-01-01
  • 2014-04-18
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 2013-05-12
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多