iggyweb
iggyweb

Reputation: 2483

MVC Add Record to Database

Could somebody please help me add a record to a database?

I have created some base elements, but I'm struggling with the code for the AccountController. I would like for a user to enter the values for Stone and Pound via the form, and on posting add a record to the Weight table along with current Id of the logged in user and current date. Here is what I have so far.

AddWeightModel

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

WebApplication1Entities

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

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

_UpdatePartial

@using Microsoft.AspNet.Identity
@model WebApplication1.Models.AddWeightModel

@using (Html.BeginForm("RecordCard", "Account", FormMethod.Post, new { @id = "contact-form", role = "form" }))
{
    <fieldset>
        @Html.AntiForgeryToken()
        @Html.ValidationSummary()
        <div class="form-div-5">
            <label>
                @Html.TextBoxFor(m => m.Stone, new { @placeholder = "Stone *", @type = "text" })
            </label>
        </div>
        <div class="form-div-5">
            <label>
                @Html.TextBoxFor(m => m.Pound, new { @placeholder = "Pound *", @type = "text" })
            </label>
        </div>             
        <div class="button-wrapper">
            <input type="submit" value="Submit" class="button" />
        </div>
    </fieldset>
}

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 ActionResult RecordCard(Weight Model)
{
    if (ModelState.IsValid)
    {
        using (WebApplication1 db = new WebApplication1())
        {
            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);
}

Please note that _UpdatePartial is called from RecordCard like so:

@Html.Partial("_WeightPartial", new AddWeightModel()) 

And also RecordCard receives an IEnumerable list:

@model IEnumerable<Shedtember.Models.Weight>

I need a list of records from the Weight table depending on logged in user to generate a graph.

Just want to add the record and return to the RecordCard page.

Please help, I'm going insane!

Upvotes: 2

Views: 7812

Answers (1)

Jonesopolis
Jonesopolis

Reputation: 25370

I'll try to break this down.

Your compile error at:

db.Weights.Add(Model);

occurs because db.Weights.Add() expects a Weight. You are passing it your model of type AddWeightModel. You need to convert your model back to a Weight:

Weight weight = new Weight();
weight.UserId = //get your current user's ID
weight.Stone = Model.Stone;
weight.Pount = Model.Pound;
weight.Date = DateTime.UTCNow;

db.Weights.Add(weight);

Next, your method

public ActionResult RecordCard(AddWeightModel Model) 

needs to be a POST, so decorate it:

[HttpPost]
public ActionResult RecordCard(AddWeightModel Model)

Now in your view you are (very correctly) adding a @Html.AntiForgeryToken(). It doesn't help you unless you validate it:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RecordCard(AddWeightModel Model)

Step back, and examine what types you are working with.

Upvotes: 2

Related Questions