MVC添加记录到数据库

本文关键字:数据库 加记录 添加 MVC | 更新日期: 2023-09-27 18:02:09

有人能帮我添加一个记录到数据库吗?

我已经创建了一些基本元素,但我正在为AccountController的代码而挣扎。我想让用户通过表单输入石头和磅的值,并在发布时添加一个记录到权重表以及登录用户的当前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);
}

请注意,_UpdatePartial是这样从RecordCard调用的:

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

并且RecordCard接收一个IEnumerable列表:

@model IEnumerable<Shedtember.Models.Weight>

我需要一个来自权重表的记录列表,这取决于登录的用户来生成一个图。

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

请帮帮我,我要疯了!

MVC添加记录到数据库

我来解释一下。

编译错误:

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)

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