Pushpendra Kuntal
Pushpendra Kuntal

Reputation: 6186

How can pass parameter in RedirectToAction?

I am working on 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?

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.

Upvotes: 13

Views: 63535

Answers (3)

Johan Olsson
Johan Olsson

Reputation: 715

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.

//
// 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)
}

Upvotes: 29

frennky
frennky

Reputation: 13934

Try this way:

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

Upvotes: 2

daniel.herken
daniel.herken

Reputation: 1105

Why not do this?

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

Upvotes: 0

Related Questions