【问题标题】:How can pass parameter in RedirectToAction?如何在 RedirectToAction 中传递参数?
【发布时间】:2011-09-25 17:57:57
【问题描述】:

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

我想将 id 传递给 ingredientIndex 操作。我该怎么做?

我想使用这个来自另一个页面的 ID public ActionResult ingredientsEdit(int id)。实际上我在第二次行动中没有id,请建议我该怎么做。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 asp.net-mvc-3


    【解决方案1】:
    return RedirectToAction("IngredientIndex", new { id = id });
    

    更新

    首先,我会将 IngredientIndex 和 IngredientEdit 重命名为 Index 和 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)
    }
    

    【讨论】:

    • 如何在 [HttpPost] 操作中使用“id”的值?
    • 看上面的例子。如果您正在编辑您的第五个项目 (/Edit/5),它会在您发布时自动将其映射到 id (int)(使用标准路由等...)。
    【解决方案2】:

    试试这个方法:

    return RedirectToAction("IngredientIndex", new { id = productFormulation.id });
    

    【讨论】:

      【解决方案3】:

      为什么不这样做?

      return RedirectToAction("ingredientIndex?Id=" + id);
      

      【讨论】:

      • 您必须在每个视图中传递 id
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2020-03-30
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多