Question

Could someone please examine the code below and tell me why UserId and Date fields are not populating?

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(WeightViewModel vModel)
{
    Weight Model = vModel.Weight;
    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 RedirectToAction("Index");
}

After I post the table Weight has a new record with Stone and Pound values but the UserId and Date are Null.

I have included below the Weight class for data references:

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; }
}

Any help would be much appreciated :-)

Was it helpful?

Solution

Because you do this:

db.Weights.Add(Model);

instead of this:

db.Weights.Add(weight);

This is a very good reason to have ViewModel classes that are not your DomainModel classes. If the ViewModel were a different Type the Add to the database context would have failed with a compilation error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top