2016-12-03 4 views
1

カテゴリに関連付けられた商品を編集したいが、編集ビューページでカテゴリテーブルを呼び出す方法がわからない。ここで.netコア編集ページ、接続テーブル

は、私が実行しようとしているコードです:

製品&カテゴリー

public class Product 
{ 
public int ProductID {get; set;} 
public string Name {get; set;} 
public Category Category {get; set;} 
} 
public class Category 
{ 
public int CategoryID {get; set;} 
public string CatName {get; set;} 
} 

リポジトリ:

public class EFProductRepository : ProductRepository 
{ 
    private AppDbContext context; 

    public EFProductRepository(AppDbContext icr) 
    { 
     context = icr; 
    } 

    public IEnumerable<Product> Products => context.Products; 

    public void SaveProduct(Product product) 
    { 
      Product dbEntry = context.Products 
      .FirstOrDefault(p => p.ProductID == product.ProductID); 
      if (dbEntry != null) 
      { 
       dbEntry.Name = product.Name; 
       dbEntry.Category = product.Category; //Don't know if that's true or not 
      } 

     context.SaveChanges(); 
    } 
} 

コントローラーコード

public class AdminController : Controller 
{ 
    private ProductRepository repo; 
    public AdminController(ProductRepository rep) 
    { 
     repo = rep; 
    } 

    public ViewResult Edit(int productID) => View(repo.Products 
      .FirstOrDefault(p => p.ProductID == productID) 
    ); 

    [HttpPost] 
    public IActionResult Edit(Product product) 
    { 
     if (ModelState.IsValid) 
     { 
      repo.SaveProduct(product); 
      TempData["message"] = $"{product.Name} saved."; 
      return RedirectToAction("Index"); 
     } 
     else 
     { 
      return View(product); 
     } 
    } 
} 

マイビューページ、私は(int型またはオブジェクト?)カテゴリを表示し、それを保存するためにここにドロップダウンを追加したい

@model Product 
<form asp-action="Edit" method="post"> 
    <input asp-for="ProductID" /> 
    <div class="form-group"> 
    <label asp-for="Name">Name</label> 
    <div><span asp-validation-for="Name" class="text-info"></span></div> 
    <input asp-for="Name" class="form-control" /> 
    </div> 
    <!-- I want to add categories dropdown list here --> 
    <div class="text-center"> 
    <button class="btn btn-primary" type="submit">Save</button> 
    </div> 
</form> 

答えて

0

この

public class Product 
{ 
public Product(){ 
category = new List<Category>(); 
} 
public int ProductID {get; set;} 
public string Name {get; set;} 
public List<Category> category {get; set;} 
} 

を例える製品クラスを作成します。そしてビューでこのように作成

@{ 

     var list = Model.catlg.Select(x => new SelectListItem { Text =x.catid, Value = x.catid }).ToList(); 
    } 

@Html.DropDownListFor(m => m.catlg, list, "-- Select Status --") 
+0

文字列をintに変換できません(x.catidの場合)エラーが発生しました。 –

関連する問題