2012-12-12 2 views
3

나는 다음과 같은보기 사용자가 제품 테이블을 가지고 있고 "수량> 0"기본값은 0입니다 모든 데이터를 선택해야합니다.하지만 내가 어떻게 해야할지 모르겠다 테이블에서 데이터를 수집합니다. 응답 해 주셔서 감사합니다.보기에서 테이블에서 여러 데이터 선택 asp.net MVC4 면도기

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
<fieldset> 
    <legend>Produkty</legend> 
    <table> 
    @foreach (var item in Model) { 
     <tr> 
      <td> 
       @Html.DisplayFor(model => item.Product.Name) 
      </td> 

      <td> 
       @Html.DisplayFor(model => item.Product.Price) 
      </td> 
      <td> 
       @Html.EditorFor(model => item.Quantity) 
      </td> 
     </tr> 
    } 
     <p> 
      <input type="submit" value="Orders" /> 
     </p> 

    </table> 
</fieldset> 
} 

// 컨트롤러

public ActionResult Index() 
    { 
     List<ProductListViewModel> productList = new List<ProductListViewModel>(); 

     foreach (var item in db.Products.ToList()) 
     { 
      ProductListViewModel model = new ProductListViewModel(); 
      model.Product = item; 
      model.Quantity = 0; 
      productList.Add(model); 
     } 

     return View(productList); 
    } 

답변

3

당신이 Html.EditorFor를 사용하고 있기 때문에, 일이 쉽다. index 액션 (Post의 경우)에 productList 매개 변수를 넣으면 MVC는 양식 데이터를 productList 객체에 자동으로 결합하므로 서버 측에서 루프로 수량을 필터링하면됩니다. 원인, 제품 개체를 식별하려면보기에서 숨겨진 ID를 추가하는 것이 좋습니다.

<table> 
@for(int i = 0; i<Model.Count; i++) { 
    <tr> 
     <td> 
      @Html.HiddenFor(model => Model[i].Product.ID) 
      @Html.DisplayFor(model => Model[i].Product.Name) 
     </td> 
     <td> 
      @Html.EditorFor(model => Model[i].Quantity) 
     </td> 
    </tr> 
} 


[HttpPost] 
public ActionResult Index(List<ProductListViewModel> productList) 
    { 
     \\... 
    } 
+0

는 그 시도했다하지만 난 항상 "제품 목록 == null이"나는 대한에 foreach 문을 변경, 대답을 업데이 트했습니다 및 작동 – Brandejs

+1

@Brandejs를 얻을. 이 메소드는 '[0] .Quantity'와 '[1] .Quantity'와 같은 입력을위한 이름을 생성 한 다음 MVC가이를 목록으로 결합합니다. – Teddy

관련 문제