2016-07-15 11 views
0

私はC#でプログラミングする方法を学ぶための基本的なWebショップを作っています。私は初心者であり、私は電子書籍、youtubeとofcourseの助けを借りてすべてを学ぶStackoverflow。今私は自分で解決できない問題に着いたので、本当に皆さんの助けが必要です。ASP.NET MVCはidを渡しません

問題は次のとおりです。メニューの 'webshop'ボタンを押すと、名前、写真、価格などのすべての自分の製品が一覧表示され、[カートに追加]ボタンが表示されます。私はこのボタンを押すと私はショッピングカートに行き、選択した数量(この時点ではデフォルトは1)とすべての製品の合計金額との価格を表示する必要があります。私がボタンを押すと私はカートに行きますが、このカートは空です。 CartControllerのAddToCartメソッドに送信しているIDはnullです...これを修正するにはどうすればよいですか?以下の関連するコードを見ることができます。

RouteConfig

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Routing; 

namespace Webshop 
{ 
public class RouteConfig 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 
    } 
} 
} 

ProductSummary(AddToCartボタンを有する部分図)

@model Webshop.Models.Entiteiten.Product 

<div class="col-md-4"> 
    @if (@Model.ImageData != null) 
     { 
    <div class="pull-left" style="margin-right: 10px"> 
     <img class="img-thumbnail" width="75" height="75" 
      src="@Url.Action("GetImage", "Product",new { @Model.ProductID })" /> 
    </div> 
} 
<h3>@Model.Name</h3> 
@Model.Description 
<h4>@Model.Price.ToString("c")</h4> 
@using (Html.BeginForm("AddToCart", "Cart")) 
     { 
    <div class="pull-right"> 
     @Html.HiddenFor(x => x.ProductID) 
     @Html.Hidden("returnUrl", Request.Url.PathAndQuery) 
     <input type="submit" class="btn btn-success" value="Add to cart" /> 
    </div> 
} 

カートモデル

事前にみんなで3210
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace Webshop.Models.Entiteiten 
{ 
    public class Cart 
{ 
    private List<CartLine> lineCollection = new List<CartLine>(); 

    public void AddItem(Product product, int quantity) 
    { 
     CartLine line = lineCollection 
     .Where(p => p.Product.ProductID == product.ProductID) 
     .FirstOrDefault(); 
     if (line == null) 
     { 
      lineCollection.Add(new CartLine 
      { 
       Product = product, 
       Quantity = quantity 
      }); 
     } 
     else { 
      line.Quantity += quantity; 
     } 
    } 
    public void RemoveLine(Product product) 
    { 
     lineCollection.RemoveAll(l => l.Product.ProductID == 
     product.ProductID); 
    } 
    public decimal ComputeTotalValue() 
    { 
     return lineCollection.Sum(e => e.Product.Price * e.Quantity); 
    } 
    public void Clear() 
    { 
     lineCollection.Clear(); 
    } 
    public IEnumerable<CartLine> Lines 
    { 
     get { return lineCollection; } 
    } 
} 
public class CartLine 
{ 
    public Product Product { get; set; } 
    public int Quantity { get; set; } 
} 
} 

CartController

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using Webshop.DB.Abstract; 
using Webshop.Models.Entiteiten; 
using Webshop.Models; 

namespace Webshop.Controllers 
{ 
public class CartController : Controller 
{ 
    private IProductRepository repository; 
    public CartController(IProductRepository repo) 
    { 
     repository = repo; 
    } 

    public ViewResult Index(string returnUrl) 
    { 
     return View(new CartIndexViewModel 
     { 
      Cart = GetCart(), 
      ReturnUrl = returnUrl 
     }); 
    } 

    public RedirectToRouteResult AddToCart(int? id, string returnUrl) 
    { 
     Product product = repository.Products 
     .FirstOrDefault(p => p.ProductID == id); 
     if (product != null) 
     { 
      GetCart().AddItem(product, 1); 
     } 
     return RedirectToAction("Index", new { returnUrl }); 
    } 

    public RedirectToRouteResult RemoveFromCart(int? id, string returnUrl) 
    { 
     Product product = repository.Products 
     .FirstOrDefault(p => p.ProductID == id); 
     if (product != null) 
     { 
      GetCart().RemoveLine(product); 
     } 
     return RedirectToAction("Index", new { returnUrl }); 
    } 

    private Cart GetCart() 
    { 
     Cart cart = (Cart)Session["Cart"]; 
     if (cart == null) 
     { 
      cart = new Cart(); 
      Session["Cart"] = cart; 
     } 
     return cart; 
    } 
} 
} 

CartIndexViewModel

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using Webshop.Models.Entiteiten; 

namespace Webshop.Models 
{ 
    public class CartIndexViewModel 
    { 
     public Cart Cart { get; set; } 
     public string ReturnUrl { get; set; } 
    } 
} 

ありがとう!

答えて

0

これは、送信している値がコントローラアクションが期待しているパラメータ名と一致しない可能性が高いためです。既存のフォームを見ると、ProductIDという名前の値をCart/AddToCartコントローラのアクション:アクションそのものを見てみた場合

<!-- This will post a value named "ProductID" to Cart/AddToCart --> 
@Html.HiddenFor(x => x.ProductID) 

は、しかし、それは代わりにidという名前のパラメータを期待しています:

public RedirectToRouteResult AddToCart(int? id, string returnUrl) 
{ 
    // Omitted for brevity 
} 

これが発生していることを理由は番目ですHiddenFor()ヘルパーに渡されたプロパティの名前に対応しname属性を持つ要素を作成するために起こっている:

<input id='ProductID' name='ProductID' type='hidden' value='{your-product-id}' /> 

これが投稿されます場合は、お使いのAddToCartコントローラのアクションはパラメータと呼ばれる表示されませんProductIDなので、マップする方法はわかりません(ちょうどidがあります)。

可能な解像度

、あなたの好みに応じて、この問題を解決することができ、いくつかのpossilbeの方法があります。

は、私は第二の溶液をしたあなたの行動

@Html.Hidden("id", Model.ProductID) 
+0

に一致するようにProductIDからidにフォームでプロパティの名前を変更し

public RedirectToRouteResult AddToCart(int? ProductID, string returnUrl) { // Omitted for brevity } 

idからProductIDにごAddToCartパラメータ名の名前を変更し、それは完全に動作します。どうもありがとうございました。私はこの問題に何時間も悩まされていました。再度、感謝します! – NathanBaele

関連する問題