MVC3将参数传递给同一控制器中的其他参数

时间:2012-04-01 21:33:55

标签: asp.net-mvc-3

我正在尝试传递参数,即< priceValue'。如何通过使用RedirectToAction传递此值?或者你对此有什么想法? 我正在尝试制作购物车。 ' priceValue'是radioButton值。你能给我一些帮助吗?在传递priceValue之后,我想使用if语句在AddToCart中编写的内容。有可能使用它吗? 请帮我.. 感谢。

public class ShoppingCartController : Controller
{
rentalDB db = new rentalDB();
    //
    // GET: /ShoppingCart/
    public ActionResult Index()
    {
        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Set up our ViewModel

        var viewModel = new ShoppingCartViewModel
        {
            CartItems = cart.GetCartItems(),
            CartTotal = cart.GetTotal()
        };

        // Return the view
        return View(viewModel);
    }


    // GET: /Store/AddToCart/5
    [HttpPost]
    public ActionResult AddToCart(int id, FormCollection col)
    {
        var addedProduct = db.Product
            .Single(product => product.productId == id);
        decimal priceValue = Convert.ToDecimal(col["price"]);
        //how to pass priceValue to index
        if (Convert.ToDecimal(col["price"]) == addedProduct.threeDayPrice)
        {
            ViewBag.price = new SelectList(db.Product, "productId", "threeDayPrice");
            //How to put this value into cart.AddtoCart(addedProduct) with date and price
        }
        else if (Convert.ToDecimal(col["price"]) == addedProduct.aWeekPrice)
        {
            ViewBag.price = new SelectList(db.Product, "productId", "aWeekPrice");
            //How to put this value into cart.AddtoCart(addedProduct) with date and price
        }

        // Retrieve the product from the database
        // Add it to the shopping cart
        var cart = ShoppingCart.GetCart(this.HttpContext);

        cart.AddToCart(addedProduct);

        // Go back to the main store page for more shopping
        //I don't know how to pass the 'priceValue' by using RedirectToAction.
        return RedirectToAction("Index", new {id = priceValue});
    }

2 个答案:

答案 0 :(得分:2)

您必须向Index方法添加一个参数,以便能够获取传递给Index方法的值:

public ActionResult Index(int priceValue = 0).

您可以使用您希望的任何默认值,而不是0。然后打电话给

return RedirectToAction("Index", new {@priceValue = priceValue});

将允许您获取方法内的值。

答案 1 :(得分:1)

return RedirectToAction("Index", new {@id = priceValue.toString()}); 

会将其重定向到名为Index的带有id参数

的Action方法