MVC - GET&在同一控制器中具有相同名称和参数的POST操作

时间:2013-06-04 11:26:52

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

我正在开发一个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 个答案:

答案 0 :(得分:5)

在GET model行动中你真的需要一个Create参数吗?你可以这样做:

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) {}
相关问题