データベースから取得したアイテムのリストから選択する方法を探しています。これらのアイテムをビューに送信し、リストから選択してコントローラーに返して、データベース内のセカンダリ テーブルに入力したいと考えています。アイテムをビューに渡して表示させることはできますが、これらのアイテムをコントローラーに戻すことができないようです。
コントローラー呼び出し (再度更新):
public ActionResult Create()
{
var myMeal = new CreateMeal();
List<ProductsToInclude> pti = new List<ProductsToInclude>();
myMeal.ProductsToInclude = pti;
IList<Product> prods = db.Products.ToList();
foreach(var prod in prods)
{
pti.Add(new ProductsToInclude { Product = prod });
}
return View(myMeal);
}
//
// POST: /Meal/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateMeal myMeal)
{
if (ModelState.IsValid)
{
/* Add code to handle my meal and create a meal for data base*/
db.Meals.Add(meal);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(pti);
}
ProductsToInclude ViewModel
public class ProductsToInclude
{
public Product Product { get; set; }
public Boolean Include { get; set; }
}
新しい CreateMeal ビューモデル:
public class CreateMeal
{
public String Name { get; set; }
public IList<ProductsToInclude> ProductsToInclude { get; set; }
}
作成ビュー:
@model MealPlanner.ViewModels.CreateMeal
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Meal</legend>
<div>
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
</div>
<div>
@Html.EditorFor(m => m.ProductsToInclude)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
そして編集者 Templete (更新済み) :
@model MealPlanner.ViewModels.ProductsToInclude
<tr>
<td>
@Html.CheckBoxFor(m => m.Include)
</td>
<td>
@Model.Product.Name
@Model.Product.Quantity
@Model.Product.unit.UnitName
@Html.HiddenFor(m => m.Product.Name)
@Html.HiddenFor(m => m.Product.Quantity)
@Html.HiddenFor(m => m.Product.unit.UnitName)
</td>
</tr>
食事モデル:
public class Meal
{
public int MealId { get; set; }
public String Name { get; set; }
//public virtual IList<Product> Products { get; set; }
public int UserId { get; set; }
}
アップデート:
EditorTemplete に切り替えると、これを表示できません。myMeal.ProductsToInclude.Add(new ProductsToInclude { Product = prod, Include = false}); でエラーが発生するようになりました。Create メソッドで。prod には 8 つの製品が含まれています。