2017-11-22 5 views
0

Asp.Net Core 2.0 MVC에서 간단한 장바구니 앱을 만들려고합니다. 나는 어떤 Ajax-ing도하지 않고있다. 나는 세 가지 모델이 있습니다모델 데이터를 뷰의 테이블과 다른 테이블에 저장할 수 있습니까?

: 아래의 두 가지보기 중 하나에서

public class Product 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    public string Info { get; set; } 
    public decimal Price { get; set; } 
} 

public class Cart 
{ 
    public int Id { get; set; } 
    public int CartItemId { get; set; } 
    public int CustomerId { get; set; } // not in use yet 
} 

public class CartItem 
{ 
    public int Id { get; set; } 
    public int ProductId { get; set; } 
    public int NumEach { get; set; } // not in use yet 
} 

을, 나는 다시 내가이 카트에 추가 버튼을 클릭 한보기로 리디렉션 후 장바구니와 CartItem를 업데이트 할

1) 색인보기 :

@model IEnumerable<simpleShop.Models.Product> 

<table class="table"> 
    <thead> 
     <tr> 
      <th>@Html.DisplayNameFor(model => model.Title)</th> 
      <th>@Html.DisplayNameFor(model => model.Info)</th> 
      <th>@Html.DisplayNameFor(model => model.Price)</th> 
      <th></th> 
     </tr> 
    </thead> 
    <tbody> 
     @foreach (var item in Model) 
     { 
      <tr> 
       <td> 
        <a asp-action="Details" asp-route-id="@item.Id"> 
         @Html.DisplayFor(modelItem => item.Title) 
        </a> 
       </td> 
       <td>@Html.DisplayFor(modelItem => item.Info)</td> 
       <td>@Html.DisplayFor(modelItem => item.Price)</td> 
       <td> 
        <form asp-action="AddToCart"> 
         <button type="submit" value="@item.Id">Add to cart</button> 
        </form> 
       </td> 
      </tr> 
     } 
    </tbody> 
</table> 

2) 세부 사항보기 : 아래

@model simpleShop.Models.Product 
@{ 
    ViewData["Title"] = Html.DisplayFor(model => model.Title); 
} 
<h2>@Html.DisplayFor(model => model.Title)</h2> 
<h4>@Html.DisplayFor(model => model.Info)</h4> 
<h1>@Html.DisplayFor(model => model.Price)</h1> 
<form asp-action="AddToCart"> 
    <input type="hidden" asp-for="Id" /> 
    <p> 
     <input type="submit" value="Add to cart" /> 
    </p> 
</form> 
<div> 
    <a asp-action="Index">Return to list</a> 
</div> 

는 내 결함 AddToCart와는-충족 카트 컨트롤러 나 CartItem 테이블에 데이터를 저장하는 작업을 현재하고 있지 않은 가정용 컨트롤러의 hod. 어떻게해야합니까? 한 가지 바인드()에 대한

[HttpPost] 
[ValidateAntiForgeryToken] 
public async Task<IActionResult> AddToCart([Bind("Id")] Product product) 
{ 
    if (ModelState.IsValid) 
    { 
     _context.Add(product); 
     await _context.SaveChangesAsync(); 
     if (product.Id > 0) // added to cart via the details-view 
     { 
      return RedirectToAction("Details", "Home", product.Id); 
     } 
     else // added to cart via the index-view 
     { 
      return RedirectToAction(nameof(Index)); 
     } 
    } 
    return View(product); 
} 
+0

현재 정확히 무슨 일이 일어나고 있습니까? AddToCart 액션에 들어가는가? 디버그에서 실행하여 흐름을 확인 했습니까? – Aeseir

+0

AddToCart 매크로가 실행 중이지만 아무 데이터도받지 못합니다. 그러나 이제는 Cart 및 CartItem 테이블이 아닌 Product 테이블에 쓰도록 설정됩니다. Product 대신 CartItem을 사용하도록 작업 방법을 변경하면 NumEach는 0, ProductId는 0이 CartItem 테이블에 저장되고 Id가없는 Home/Details로 리다이렉되어 404가 발생합니다. - 만약 product.Id (또는 cartItem.ID, 그것을 변경하면, 상관 없다)가 0보다 크다면 Home/Details + Id로 리다이렉트한다. – Stian

답변

0

는 새로운 액션에 전달하고 싶었다 개체의 문제의 모든 속성을 포함하는 당신이 결합하고 싶었다 적 기억, 그냥 "아이디"보다 훨씬 더 많이 필요합니다. 라인

참조 주석 - >>

나의 제안은 당신이 제품의 제품 ID 및 수량 (당신의 NumEach)하지만 장바구니에

[HttpPost] 
[ValidateAntiForgeryToken] 
public asyync Task<IActionResult> AddToCart([Bind("ProductId", "NumEach", "CartId")] CartItem model, string ReturnUrl){ 
    if(ModelState.IsValid){ 

     _context.CartItem.Add(model); 

     await _context.SaveChangesAsync(); 

     //model.Id greater than 0 indicates a save occurred. 
     if(model.Id > 0) 
      return RedirectToAction(ReturnUrl); // forced return for further shopping? 
     else 
      return RedirectToAction("Index");  
    } 

    //this assumes bad model state with no error unless model is 
    //annotated accordingly. 

    return View(model); 
} 

문제가됩니다 이러한 라인을 따라 간다

[HttpPost] 
[ValidateAntiForgeryToken] 
public async Task<IActionResult> AddToCart([Bind("Id")] Product product) 
{ 
    if (ModelState.IsValid) 
    { 
     _context.Add(product); //**BAD this will probably try to 
           // add product to the product table again.** 
           // With error to follow about already exists 
           // exception at the SaveChangesAsync call. 
     await _context.SaveChangesAsync(); 

     if (product.Id > 0) 
     { 
      return RedirectToAction("Details", "Home", product.Id); 
     } 
     else // added to cart via the index-view 
     { 
      return RedirectToAction(nameof(Index)); 
     } 
    } 
    return View(product); 
} 

지금은 1 품목 만 저장할 수 있습니다 ...

public class Cart{ 
    public Cart(){} 


    public int Id {get;set;} //cart's integer id 

    public List<CartItem> CartItems {get;set;} //collection of cartitems 

    //FK 
    public int CustomerId {get;set;} //customer's id 
    //NAV 
    public Customer CustomerId {get;set;} //customer nav 
    ... 
} 

public class CartItem{ 
    public CartItem(){} 

    public int Id {get;set;}   //cart item id 

    public int ProductId {get;set;} //productid 
    public Product Product {get;set;} //nav property 

    public int NumEach {get;set;}  //quantity of each product 

    //FK 
    public int CartId {get;set;}  //Foreign Key 
    //NAV 
    public Cart Cart {get;set;}  //nav property 
} 

x보기는 모델을 제품 모음으로 만 사용하는 것이 아니라 제품 모음을 포함하는 viewmododel이지만 방문자와 함께 생성 된 cartid도 포함합니다. CartId는 트랜잭션이 완료 될 때까지 해당 방문자를 추적하고 OrderId를 갖거나 세션이 닫히면 종료됩니다.

@model simpleShop.Models.IndexViewModel 

<table class="table"> 
    <thead> 
     <tr> 
      <th>@Html.DisplayNameFor(model => model.Title)</th> 
      <th>@Html.DisplayNameFor(model => model.Info)</th> 
      <th>@Html.DisplayNameFor(model => model.Price)</th> 
      <th></th> 
     </tr> 
    </thead> 
    <tbody> 
     @foreach (var item in Model.Products) 
     { 
      <tr> 
       <td> 
        <a asp-action="Details" asp-route-id="@item.Id"> 
         @Html.DisplayFor(modelItem => item.Title) 
        </a> 
       </td> 
       <td>@Html.DisplayFor(modelItem => item.Info)</td> 
       <td>@Html.DisplayFor(modelItem => item.Price)</td> 
       <td> 
        <form asp-action="AddToCart"> 
         <input type="Hidden" asp-for="@Model.CartId" /> 

         <button type="submit" value="@item.Id">Add to cart</button> 
        </form> 
       </td> 
      </tr> 
     } 
    </tbody> 
</table> 


public class IndexViewModel 
{ 
    public IndexViewModel(){} 

    public int CartId{get;set;} 
    public List<Product> Products{get;set;} 
} 

나는 거기에서 아이디어를 얻습니다.