有人可以提供一个如何在一个视图中组合两个模型的示例吗?
目前我有一个名为 RecordCard 的页面,其中包含:
@model IEnumerable<WebApplication1.Models.Weight>
这是由 AccountController 中的以下代码提供的:
public ActionResult RecordCard()
{
var UserId = User.Identity.GetUserId();
var weightModel = from m in db.Weights where m.UserId == UserId select m;
return View(weightModel);
}
RecordCard 页面还包含一个绑定到以下类的表单:
public class AddWeightModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Stone")]
public Nullable<short> Stone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Pound")]
public Nullable<short> Pound { get; set; }
}
但是,这是两个具有不同用途的单独模型,因此如何组合成一个包含 IEnumerable 列表和表单元素集的单个模型,这些元素最终将正确发布到 AccountController 以使用以下代码将记录添加到数据库:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(Weight Model)
{
if (ModelState.IsValid)
{
using (WebApplication1Entities db = new WebApplication1Entities())
{
Weight weight = new Weight();
weight.UserId = User.Identity.GetUserId();
weight.Stone = Model.Stone;
weight.Pound = Model.Pound;
weight.Date = System.DateTime.Now;
db.Weights.Add(Model);
db.SaveChanges();
}
}
return View(Model);
}
我已经包括了下面的重量等级:
public partial class Weight
{
public int Id { get; set; }
public string UserId { get; set; }
public Nullable<short> Stone { get; set; }
public Nullable<short> Pound { get; set; }
public Nullable<System.DateTime> Date { get; set; }
}
这里还有 WebApplication1 Entities 类,它将权重表声明为 Weights:
public partial class WebApplication1Entities : DbContext
{
public WebApplication1Entities()
: base("name=WebApplication1Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Weight> Weights { get; set; }
}
请解释一下需要修改什么,以及无论我尝试阅读、遵循和实施什么,我似乎都遗漏了一些东西。
任何帮助将非常感激 :-)