能否请提供一个将两个模型合并到一个视图中的示例?
目前,我有一个名为 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);
}
记录卡页面还包含一个表单,该表单与以下类绑定:
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列表和一组表单元素的单个模型,最终可以使用以下代码正确地将记录添加到数据库中:
[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);
}
我已经包含了下面的Weight类:
我已经包含了下面的Weight类:
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; }
}
这里还有一个WebApplication1Entities类,它将Weight表声明为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; }
}
请解释需要如何进行修改,无论我尝试阅读、跟随和实现什么,似乎总是缺少某些东西。 任何帮助都将不胜感激 :-)