asp.net-mvc 如何在 RedirectToAction 中传递参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6531190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can pass parameter in RedirectToAction?
提问by Pushpendra Kuntal
I am working on MVC asp.net.
我正在开发 MVC asp.net。
This is my controller action:
这是我的控制器操作:
public ActionResult ingredientEdit(int id) {
ProductFormulation productFormulation = db.ProductFormulation.Single(m => m.ID == id);
return View(productFormulation);
}
//
// POST: /Admin/Edit/5
[HttpPost]
public ActionResult ingredientEdit(ProductFormulation productFormulation) {
productFormulation.CreatedBy = "Admin";
productFormulation.CreatedOn = DateTime.Now;
productFormulation.ModifiedBy = "Admin";
productFormulation.ModifiedOn = DateTime.Now;
productFormulation.IsDeleted = false;
productFormulation.UserIP = Request.ServerVariables["REMOTE_ADDR"];
if (ModelState.IsValid) {
db.ProductFormulation.Attach(productFormulation);
db.ObjectStateManager.ChangeObjectState(productFormulation, EntityState.Modified);
db.SaveChanges();
**return RedirectToAction("ingredientIndex");**
}
return View(productFormulation);
}
I want to pass id to ingredientIndex
action. How can I do this?
我想将 id 传递给ingredientIndex
行动。我怎样才能做到这一点?
I want to use this id public ActionResult ingredientEdit(int id)which is coming from another page. actually I don't have id
in second action, please suggest me what should I do.
我想使用这个来自另一个页面的id公共 ActionResult 成分编辑(int id)。实际上我没有id
第二个动作,请建议我该怎么做。
回答by Johan Olsson
return RedirectToAction("IngredientIndex", new { id = id });
Update
更新
First I would rename IngredientIndex and IngredientEdit to just Index and Edit and place them in IngredientsController, instead of AdminController, you can have an Area named Admin if you want.
首先,我将 IngredientIndex 和 IngredientEdit 重命名为 Index 和 Edit 并将它们放置在成分控制器中,而不是 AdminController,如果需要,您可以拥有一个名为 Admin 的区域。
//
// GET: /Admin/Ingredients/Edit/5
public ActionResult Edit(int id)
{
// Pass content to view.
return View(yourObjectOrViewModel);
}
//
// POST: /Admin/Ingredients/Edit/5
[HttpPost]
public ActionResult Edit(int id, ProductFormulation productFormulation)
{
if(ModelState.IsValid()) {
// Do stuff here, like saving to database.
return RedirectToAction("Index", new { id = id });
}
// Not valid, show content again.
return View(yourObjectOrViewModel)
}
回答by daniel.herken
Why not do this?
为什么不这样做?
return RedirectToAction("ingredientIndex?Id=" + id);
回答by frennky
Try this way:
试试这个方法:
return RedirectToAction("IngredientIndex", new { id = productFormulation.id });