Проблема с ModelBinding в ASP.NET MVC - PullRequest
0 голосов
/ 01 февраля 2010

Методы из моего класса контроллера

 public RedirectToRouteResult AddToCart(Cart cart, int productID, string returnUrl)
            {
                Product product = productsRepository.Products.FirstOrDefault(p => p.ProductID == productID);
                cart.AddItem(product, 1);
                return RedirectToAction("Index", new { returnUrl });
            }

 public ViewResult Index(Cart cart, string returnUrl)
        {
            ViewData["returnUrl"] = returnUrl;
            ViewData["CurrentCategory"] = "Cart";
            return View(cart);
        }

Я также реализовал ModelBinder следующим образом:

public class CartModelBinder : IModelBinder
{
    private const string cartSessionKey = "_cart";

    #region IModelBinder Members

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.Model != null)
            throw new InvalidOperationException("Cannot update instances");
        Cart cart = (Cart)controllerContext.HttpContext.Session[cartSessionKey];
        if (cart == null)
        {
            cart = new Cart();
            controllerContext.HttpContext.Session["cartSessionKey"] = cart;
        }
        return cart;
    }
    #endregion
}

Я не получаю информацию о корзине в моем представлении индекса, поэтому она отображает мою корзину покупок как пустую. Не уверен, что происходит, но я определенно не вижу корзину в методе действия Index.

Кроме того, мой взгляд

    <content name="TitleContent">
    SportsStore: Your Cart  
</content>
<content name="MainContent">
    <viewdata model="DomainModel.Entities.Cart"/>   
    <h2>Your Cart</h2>
    <table width="90%" align="center">
        <thead><tr>
            <th align="center">Quantity</th>
            <th align="center">Item</th>
            <th align="center">Price</th>
            <th align="center">SubTotal</th>
        </tr></thead>
        <tbody>
         <for each = "var line in Model.Lines" >             
            <tr>
              <td align="center">${line.Quantity}</td> 
              <td align="left">${line.Product.Name}</td> 
              <td align="right">${line.Product.Price.ToString("c")}</td> 
              <td align="right">${(line.Quantity * line.Product.Price).ToString("c")}</td> 
            </tr>           
         </for>
       </tbody>
       <tfoot><tr>
           <td colspan="3" align="right">Total:</td>
           <td align="right">
               ${Model.ComputeTotalValue().ToString("c")}
           </td>
       </tr></tfoot>
    </table>
    <p align="center" class="actionButtons"/>
        <a href="${Html.Encode(ViewData["returnUrl"])}">Continue Shopping</a>
    </p>
</content>

1 Ответ

1 голос
/ 01 февраля 2010

RedirectToAction не передает никакой информации.он выполняет только обычное перенаправление HTTP.

Почему бы не сделать:

public ViewResult AddToCart(Cart cart, int productID, string returnUrl)
{
      Product product = productsRepository.Products
                                   .FirstOrDefault(p => p.ProductID == productID);
      cart.AddItem(product, 1);

      ViewData["returnUrl"] = returnUrl;
      ViewData["CurrentCategory"] = "Cart";
      return View("Index", cart);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...