【发布时间】:2013-04-28 18:00:36
【问题描述】:
我正在寻找一种方法来从我从数据库中检索到的项目列表中进行选择。我将这些项目发送到一个视图,我想从列表中进行选择并将其返回给控制器以填充数据库中的辅助表。我可以将项目传递给视图并让它们显示,但我似乎无法将这些项目传递回控制器。
控制器调用(再次更新):
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 个产品。
【问题讨论】:
-
我看到了很可能是问题所在的潜在错误,但为了给您一个完整的答案,您能否使用 Meal 课程的代码更新您的问题?
-
您在回发中检查过请求的表单数据吗?它有没有你需要的东西,只是命名与你所期望的不同?
-
@PeteGO 返回表单数据为空
-
说“我遇到错误”然后不包括该错误是毫无意义的。
-
@Mystere Man - 抱歉正在编辑中。尝试 myMeal.ProductsToInclude.Add(new ProductsToInclude { Product = prod, Include = false});在创建方法中
标签: c# asp.net-mvc asp.net-mvc-4 razor partial-views