MVC - 在同一控制器中使用相同名称和参数的GET和POST动作

3

我正在开发一个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);
}

1
您还可以使用ActionName属性,使Create和Update方法具有相同的签名。 - Kyle
1个回答

5

在执行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的一些基本知识。现在我已经将我的Clone操作设置为返回Create视图与模型,而不是重定向到Create方法并尝试发送模型。对于这个愚蠢的问题请原谅我。 - Owen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接