MVC将记录添加到数据库

时间:2014-05-07 19:31:05

标签: c# asp.net database forms asp.net-mvc-5

有人可以帮我把记录添加到数据库吗?

我已经创建了一些基本元素,但我正在努力使用AccountController的代码。我希望用户通过表单输入Stone和Pound的值,并在发布时向Weight表添加记录以及登录用户的当前ID和当前日期。这是我到目前为止所拥有的。

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

重量

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

请注意,从RecordCard调用_UpdatePartial,如下所示:

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

并且RecordCard还收到一个IEnumerable列表:

@model IEnumerable<Shedtember.Models.Weight>

我需要权重表中的记录列表,具体取决于登录用户生成图表。

只想添加记录并返回RecordCard页面。

请帮助,我疯了!

1 个答案:

答案 0 :(得分:2)

我试着打破这个。

您的编译错误:

db.Weights.Add(Model);
发生

是因为db.Weights.Add()需要Weight。您传递的是AddWeightModel类型的模型。您需要将模型转换回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);

接下来,你的方法

public ActionResult RecordCard(AddWeightModel Model) 

需要是一个POST,所以装饰它:

[HttpPost]
public ActionResult RecordCard(AddWeightModel Model)

现在在您的视图中,您(非常正确地)添加了@Html.AntiForgeryToken()。除非您验证它,否则它对您没有帮助:

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

退后一步,检查您正在使用的类型。