我正在寻找一种方法来从我从数据库中检索的项目列表中进行选择。我将这些项目发送到一个视图,我想从列表中进行选择并将其返回给控制器以填充数据库中的辅助表。我可以将项目传递给视图并让它们显示,但我似乎无法将这些项目传递回控制器。
控制器调用(再次更新):
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 视图模型
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}); 在创建方法中。prod 已填充,其中包含 8 个产品。