模型状态是有效的并且成功消息显示但没有数据添加到数据库

时间:2017-09-25 17:26:10

标签: c# asp.net-mvc-5 entity-framework-6

我有一个接受用户数据的应用程序,然后将其添加到数据库中。如果成功添加数据,则会显示成功消息。但是,当我测试它时,我得到了成功消息,但没有数据被添加到数据库中。

我最初使用Entity Framework创建了视图。最初该模型不包含IsCovered字段。我后来添加了,并从数据库更新了模型。在我这样做之后,它停止向数据库添加数据。

这是我的控制器:

// POST: Shifts/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ShiftID,Date,StartTime,EndTime,StoreNum,Id,IsCovered")] Shift shift)
    {
        if (ModelState.IsValid)
        {
            shift.Id = User.Identity.GetUserId();
            shift.StoreNum = User.StoreNum();
            db.SaveChanges();
            TempData["Success"] = "Shift posted for " + shift.Date.ToString("mm/dd/yyyy") + " at store #" + shift.StoreNum + " successfully.";
            return RedirectToAction("Create", "Shifts");
        }

        return View(shift);
    }

这是我的模特:

    public partial class Shift
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Shift()
    {
        this.CoveredShifts = new HashSet<CoveredShift>();
    }

    public int ShiftID { get; set; }
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode =true)]
    public System.DateTime Date { get; set; }
    [DisplayFormat(DataFormatString = "{0:HH:mm tt}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Time)]
    [Display(Name="Start Time")]
    public System.DateTime StartTime { get; set; }
    [DisplayFormat(DataFormatString = "{0:HH:mm tt}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Time)]
    [Display(Name ="End Time")]
    public System.DateTime EndTime { get; set; }
    [Display(Name ="Store Number")]
    public string StoreNum { get; set; }
    public string Id { get; set; }
    public bool IsCovered { get; set; }

    public virtual AspNetUser AspNetUser { get; set; }
    public virtual Store Store { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<CoveredShift> CoveredShifts { get; set; }
}

以下是我的观点:

@model SSM_V5.Models.Shift
@{
ViewBag.Title = "Post a Shift";
}
@using Microsoft.AspNet.Identity
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.3/themes    /smoothness/jquery-ui.css" type="text/css" />
<script src="https://code.jquery.com/jquery-2.2.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.8.1/jquery.timepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-timepicker/1.8.1/jquery.timepicker.min.css" type="text/css" />
<script language="javascript" type="text/javascript">
    $(function () {
        $('.datepicker').datepicker({
            showOptions: { speed: 'fast' },
            changeMonth: true,
            changeYear: true,
            dateFormat: 'MM/dd/yy',
            gotoCurrent: true
        });
        $('.timepicker').timepicker();
    });   
</script>
</head>
<h2>Post a Shift</h2>


@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    @if (TempData["Success"] != null)
    {
        <p class="alert alert-success" id="successMessage">@TempData["Success"]</p>
    }
    <h4>Please add your shift details below.</h4>
    <hr />
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.StoreNum)
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Date, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control datepicker" } })
            @Html.ValidationMessageFor(model => model.Date, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.StartTime, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10" >
            @Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { @class = "form-control timepicker" } })
            @Html.ValidationMessageFor(model => model.StartTime, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.EndTime, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @class = "form-control timepicker" } })
            @Html.ValidationMessageFor(model => model.EndTime, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-8">
            <input type="submit" value="Post Shift" class="btn btn-success" />
        </div>
        </div>
        </div>

我们非常了解这个问题,以及有关我的代码的一般反馈。

1 个答案:

答案 0 :(得分:0)

这是因为您没有向控制器中的数据库添加任何内容。

您只是保存更改..在这种情况下,没有任何意义,因为您没有向数据库添加任何内容。

你错过了这一行:

db.Shifts.Add(shift); // missing line
db.SaveChanges();

请告诉我这是否有帮助!