【问题标题】:Persisting Data To SQL Server via ASP.NET MVC通过 ASP.NET MVC 将数据持久化到 SQL Server
【发布时间】:2017-04-21 03:01:19
【问题描述】:

我正在尝试将“拍卖”变量中的信息保存到尚未创建的“拍卖”表中。我理解,实体框架应该为我创建它。如您所见,我的程序已将表单数据包含在“拍卖”变量中。但正如您所见,调试器在“db.Auction.Add(auction)”上停止。

为什么程序不让数据库将“拍卖”变量中的数据添加到拍卖表中?

我会很感激的。 谢谢, 厘米 感谢您到目前为止的回复,但这些建议不起作用。我已经在我的代码中编写了代码,并再次显示了错误消息,这与我启动此线程时的消息相同。

观点

@model MvcAuction.Models.Auction
@{
ViewBag.Title = "CreateAuctionItem";
}

<h2>@ViewBag.Title.</h2>

<div id="createAuctionItemSection">
    @using (Html.BeginForm("Create", "Auctions", FormMethod.Post,
                            new { @class = "form-horizontal", @id = 
"registerForm", role = "form" }))

    {
        @Html.AntiForgeryToken()
        <h4>Create An Item For Auction.</h4>

        <hr />
        @Html.ValidationSummary("", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(m => m.Title, new { @class = "col-md-2 control-
label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Title, new { @class = "form-control", @id = "title" })
        </div>
    </div>


    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.StartDate, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.StartDate, "{0:yyyy-MM-dd}", new { type = "date" })

        </div>
    </div>

    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.EndDate, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.EndDate, "{0:yyyy-MM-dd}", new { type = "date" })

        </div>
    </div>

    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.DeliveryCost, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.DeliveryCost, new { @class = "form-control", @id = "deliveryCost" })
        </div>
    </div>

    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.StartBid, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.StartBid, new { @class = "form-control", @id = "startBid" })
        </div>
    </div>

    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.BuyNowPrice, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.BuyNowPrice, new { @class = "form-control", @id = "buyNowPrice" })
        </div>
    </div>

    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.BuyNowEnabled, new { @Value = "Show Buy Now Price?", @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.CheckBoxFor(m => m.BuyNowEnabled, new { @class = "form-control", @id = "buyNowEnabled" })
        </div>
    </div>

    @Html.ValidationSummary("", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(m => m.Description, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Description, new { @class = "form-control", @id = "description" })
        </div>
    </div>


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Create Item" />
        </div>
    </div>
}
<img src="~/Content/Images/progress.gif" id="progress" style="display:none;" />
<h3>@ViewBag.TheMessage</h3>
</div><!--End createAuctionItemSection-->

模型

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace MvcAuction.Models
{
      public class Auction
{
    public long Id { get; set; }

    [Required]
    [Column(TypeName = "varchar")]
    [Display(Name = "Title")]
    public String Title { get; set; }

    public string ImageURL { get; set; }

    [Required]
    [Column(TypeName = "date")]
    [Display(Name = "Start Date")]
    public DateTime StartDate { get; set; }

    [Required]
    [Column(TypeName = "date")]
    [Display(Name = "End Date")]
    public DateTime EndDate { get; set; }

    [Required]
    [Column(TypeName = "decimal")]
    [Display(Name = "Delivery Cost")]
    public decimal DeliveryCost { get; set; }

    [Required]
    [Column(TypeName = "decimal")]
    [Display(Name = "Start Bid")]
    public decimal StartBid { get; set; }

    [Column(TypeName = "decimal")]
    [Display(Name = "Buy Now Price")]
    public decimal BuyNowPrice { get; set; }

    [Column(TypeName = "bool")]
    [Display(Name = "Buy Now Enabled")]
    public Boolean BuyNowEnabled { get; set; }

    [Column(TypeName = "varchar")]
    [Display(Name = "Description")]
    public String Description { get; set; }

    [Column(TypeName = "int")]
    [Display(Name = "View Count")]
    public int ViewCount = 0;

    public decimal? getCurrentTopBid()
    {
        return StartBid;
    }
}

}

控制器动作

    [HttpPost]
    public ActionResult Create(Auction auction )
    {
        if (ModelState.IsValid)
        {
            var db = new AuctionsDataContext();
            db.Auction.Add(auction);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View();
   }

【问题讨论】:

  • 该异常意味着auction 中没有数组或列表元素(检查Models.Auction 是否至少包含要插入的行数据)。还包括您的视图代码、模型绑定,并避免将代码逻辑发布为图像截图。
  • Action 作为 DbSet 已经是 DbContext 类的一部分。代码只能是db.Add(auction);
  • 请看我下面的回复。谢谢。
  • 请提供 DbContext 派生类 通常模板会将 _context 放在 Controller 类的顶部,在您的情况下为 private readonly AuctionsDataContext _context;,因此不需要在 create 方法中声明它。此外,如果您在 SQL Server 对象资源管理器中连接了服务器,并且在项目数据文件夹下有一个迁移文件夹,那么应该在运行/调试项目时创建表
  • 另外,模型类中的getCurrentTopBid()方法是做什么的?模型应该只包含其他类的属性和集合指针。

标签: sql-server asp.net-mvc database


【解决方案1】:

Action 已经作为 DbSet 属于 DbContext 类。此外,视图已经将模型信息发回,您不需要将其作为重载参数。将您的创建帖子更改为

public class AuctionsController : Controller
{
    private readonly AuctionsDataContext_context;

    public AuctionsController(AuctionsDataContext context)
    {
        _context = context;    
    }

    public ActionResult Create ( Bind[("Id,Title,StartDate,EndDate,DeliveryCost,StartBid,BuyNowPrice,BuyNowEnabled,Description")] Auction auction)
    {
        if (ModelState.IsValid)
       {
           _context.Add(auction);
           await _context.SaveChangesAsync();
           return RedirectToAction("Index");
       }
       return View();
  }

【讨论】:

  • @ChrisMazzochi 这不是更新的回复,这是一个不是答案的答案。您还声称没有任何建议不起作用,但未能解释它所说的内容。
  • @ChrisMazzochi 我只是在重复自己制作 cmets 的地方。更新了我的答案,解释你在做出我建议的改变时得到了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多