Can someone provide an example of how to combine two models in one view?
I currently have a page called RecordCard that contains:
@model IEnumerable<WebApplication1.Models.Weight>
This is ensured by the following code in the 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); }
The RecordCard page also contains a form bound to the following class:
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; } }
However, these are two separate models with different goals, so how can I combine with one model that contains an IEnumerable list and a set of form elements that will ultimately be correctly sent to the AccountController to add an entry to the database using the following code:
[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); }
I have included the weight class below:
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; } }
Also introduced is the WebApplication1Entities class, which declares a weight table as a weight:
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; } }
Please explain what needs to be changed and how, no matter what I try to read, follow and follow, I seem to be missing something.
Any help would be greatly appreciated :-)