如何在RedirectToAction中传递参数?

Pus*_*tal 10 asp.net-mvc asp.net-mvc-3 asp.net-mvc-2

我正在研究MVC asp.net.

这是我的控制器动作:

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);
}
Run Code Online (Sandbox Code Playgroud)

我想将id传递给ingredientIndexaction.我怎样才能做到这一点?

我想使用这个来自另一个页面的id 公共ActionResult ingredientEdit(int id).实际上我没有id第二个动作,请建议我该怎么做.

Joh*_*son 26

return RedirectToAction("IngredientIndex", new { id = id });
Run Code Online (Sandbox Code Playgroud)

更新

首先,我将IngredientIndex和IngredientEdit重命名为Index and Edit并将它们放在IngredientsController中,而不是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)
}
Run Code Online (Sandbox Code Playgroud)

  • 如何在[HttpPost]动作中使用"id"的值. (2认同)

dan*_*ken 0

为什么不这样做呢?

return RedirectToAction("ingredientIndex?Id=" + id);
Run Code Online (Sandbox Code Playgroud)