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

最佳答案

您是否真的需要在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) {}

07-25 22:58
查看更多