Sending a list using RedirectToAction in MVC4

2020-02-16 03:06发布

I am having the following code

        public ActionResult Item_Post()
    {
        List<Product> products=new List<Product>() ;
        int? total=0;
       HttpCookie cookie= Request.Cookies["myvalue"];
       if (Request.Cookies["myvalue"] != null)
       {
           int count = Request.Cookies["myvalue"].Values.Count;
               var s = Request.Cookies["myvalue"].Value;
               s = HttpUtility.UrlDecode(s ?? string.Empty);
               string[] values = s.Split(',').Select(x => x.Trim()).ToArray();                      
               for (int i = 1; i < values.Length; i++)
               {
                   int id = Convert.ToInt32(values[i]);
                   Product product = db.Products.Single(x => x.Id == id);                       
                   total+=product.Price;
                   products.Add(product);
               }
               ViewBag.total = total;     
           TempData["products"]=products;   
       }
       Session["prod"] = products;
       return View("Buy", products);
       //return RedirectToAction("Buy");
    }

Now when I use only return View("Buy", products) I am getting the output and the Url remains same as I want to change the Url and when I use

return RedirectToAction("Buy", products);

I am getting error as I want to post the form to Buy. Are the parameters passed within the RedirectToAction appropriate or does it require anything else. Here is the Action

@model IEnumerable<Shop_Online.com.Models.Product>
@{
ViewBag.Title = "Buy";
}
@using (Html.BeginForm())
{
<div style="width: 860px; margin: 0 auto" class="main">
    <table border="1" style="font-family: Verdana; font-size: 13px">
        <tr style="background-color: #f2f2f2">
            <th colspan="4">ITEM</th>
            <th>DELIEVERY DETAILS</th>
            <th>QTY</th>
            <th>SUB TOTAL</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td colspan="4" style="width: 46%">
                    <table style="font-family: Verdana; font-size: 13px">
                        <tr>
                            <td>
                                <img src="@Url.Content(item.Photo)" alt="Image" style="width:36px" />
                            </td>
                            <td>
                                @Html.DisplayFor(x => item.Model_Name)
                            </td>
                        </tr>
                        <tr>
                            <td style="color: #ccc">30 days Replacement</td>
                        </tr>
                    </table>
                </td>
                <td style="width: 39%">Free Delievery Delivered in 2-3 business days.</td>
                <td style="width: 5%">1</td>
                <td style="width: 50%"><b>Rs. @Html.DisplayFor(x => item.Price)</b></td>
            </tr>
        }
    </table>
    <div style="width: 100%; height: 70px; background-color: #f2f2f2">
        <div style="width: 75%; height: 70px; float: left; font-family: Verdana; font-size: 13px">
        </div>
        <div style="width: 25%; height: 70px; float: left; font-family: Verdana; padding-top: 20px; font-size: 13px">
            Estimated Price: <b>Rs.@ViewBag.total</b>
        </div>
    </div>
    <div class="order" style="width: 100%; height: 70px">
        <div class="left-order" style="width: 75%; height: 70px; float: left"></div>
        <div class="left-order" style="width: 25%; float: left; height: 70px">
            <input type="button" value="PLACE ORDER" style="border: 1px solid #ec6723; width: 216px; cursor: pointer; height: 45px; color: #fff; background: -webkit-linear-gradient(top,#f77219 1%,#fec6a7 3%,#f77219 7%,#f75b16 100%)" onclick="return confirm('Successfull placed order')" />
        </div>

    </div>
</div>
}

And now how should I replace the below code within my View If I use TempData

@foreach(var item in Model)
{
 @Html.DisplayFor(model=>model.Name
 /some more code/
}

3条回答
别忘想泡老子
2楼-- · 2020-02-16 03:44

You cannot get the list or any model objects passed to RedirectToAction in your action method. Because a RedirectToAction causes HTTP 302 (Redirect) request, which makes the browser to call GET request to the action.

You should use TempData to preserve the data in Item_Post action method.

public ActionResult Item_Post()
    {
        List<Product> products=new List<Product>() ;
        int? total=0;
       HttpCookie cookie= Request.Cookies["myvalue"];
       if (Request.Cookies["myvalue"] != null)
       {        
        some logic here
       }  
       //save it to TempData for later usage
       TempData["products"] = products;

       //return View("Buy", products);
       //return RedirectToAction("Buy", new {id=products});

       return RedirectToAction("Buy");
    }

And now in the Buy action use TempData to get your data.

[HttpGet]
public ActionResult Buy()
{
    var products = TempData["products"];
    //.. do anything
}

Hope this helps.


UPDATE

use the following code for Buy action.

[HttpGet]
        public ActionResult Buy()
        {
            var products = TempData["products"] as List<Product>;
            return View(products);
        }

And now in the view, use foreach over the list of elements in the products

@model IEnumerable<Shop_Online.com.Models.Product>

@foreach (var item in Model)
{
    <div>
        Item Id: @item.Id
    </div>
    <div>
        Item name: @item.Name
    </div>
}

Now this should display you the list of all the items.

Or instead of assigning the TempData to an object of model class you can also try the following code which is the replacement for the above foreach.

@if (TempData["products"] != null)
{
    foreach (var item in TempData["products"] as List<Product>)
    {
        <div>
            Item Id: @item.Id
        </div>
        <div>
            Item name: @item.Name
        </div>
    }
}
查看更多
Anthone
3楼-- · 2020-02-16 03:50

You can pass array of products as id from RedirctToAction.

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction%28v=vs.118%29.aspx

It accept RouteParamter or just value that you pass in query string of url.

If you want to use RedirectToAction then I suggest that you should use TempData.

public ActionResult Item_Post()
    {
        List<Product> products=new List<Product>() ;
        int? total=0;
       HttpCookie cookie= Request.Cookies["myvalue"];
       if (Request.Cookies["myvalue"] != null)
       {        
        some logic here
       }                   
       TempData["Products"] = products;
       return RedirectToAction("Buy");
    }

In your Buy Action

 public ActionResult Buy()
{
   // Get value from TempData
   var products=  (List<Product>)TempData["Products"];
}
查看更多
家丑人穷心不美
4楼-- · 2020-02-16 03:56

Is your Buy ActionResult accept a List<Product> as a parameter, something like:

public ActionResult Buy(List<Product> ids)
{
    ...
}

Without this it will not know what to do with the list of products

查看更多
登录 后发表回答