2011-06-30 29 views
10

Tôi đang làm việc trên MVC asp.net.Làm cách nào để chuyển tham số trong RedirectToAction?

Đây là hành động điều khiển của tôi:

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

Tôi muốn vượt qua id để ingredientIndex hành động. Tôi có thể làm cái này như thế nào?

Tôi muốn sử dụng id này Hành động công khaiThành phần sửa đổi (int id) đến từ một trang khác. thực sự tôi không có id trong hành động thứ hai, vui lòng đề nghị tôi nên làm gì.

Trả lời

0

Tại sao không thực hiện việc này?

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

Sir xin vui lòng kiểm tra Câu hỏi đã chỉnh sửa của tôi. –

+0

Bạn sẽ phải chuyển id dọc theo mỗi chế độ xem –

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

Cập nhật

Trước tiên tôi xin đổi tên IngredientIndex và IngredientEdit chỉ Index và Chỉnh sửa và đặt chúng trong IngredientsController, thay vì AdminController, bạn có thể có một vùng tên quản trị nếu bạn muốn.

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

làm cách nào tôi có thể sử dụng giá trị của "id" trong hành động [HttpPost].? –

+0

Nhìn vào ví dụ trên. Nếu bạn đang chỉnh sửa mục thứ năm của bạn (/ Edit/5), nó sẽ tự động ánh xạ nó tới id (int) khi bạn POST (với các tuyến tiêu chuẩn và vân vân ...). –

0

Hãy thử cách này:

return RedirectToAction("IngredientIndex", new { id = productFormulation.id }); 
Các vấn đề liên quan