Owe*_*wen 3 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");
}
Run Code Online (Sandbox Code Playgroud)
我想将现有模型传递到Create方法的原因是克隆然后修改现有模型.
显然编译器不喜欢这样,所以我改变了一个方法看起来像这样:
[HttpPost]
public ActionResult Create(CreateBananaViewModel model, int? uselessInt)
{
// Model Save Code...
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
这完全可以接受吗?或者有更好的解决这个问题的方法吗?
编辑/解决方案:
看起来我完全过度复杂的情况.这是我的解决方案
public ActionResult Duplicate(Guid id)
{
var banana = GetBananaViewModel(id);
return View("Create", model);
}
public ActionResult Create()
{
var model = new CreateBananaViewModel();
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
model
在GET Create
行动中你真的需要一个参数吗?你可以这样做:
public ActionResult Create()
{
var model = new CreateBananaViewModel();
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望收到一些查询数据到该操作(www.mysite.com/banana/create?bananaType=yellow
)
public ActionResult Create(string bananaType, string anotherQueryParam)
{
var model = new CreateBananaViewModel()
{
Type = bananaType
};
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
并按原样保留你的POST动作
[HttpPost]
public ActionResult Create(CreateBananaViewModel model) {}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7443 次 |
最近记录: |