值不能为空.参数名称:实体

本文关键字:实体 参数 不能 | 更新日期: 2023-09-27 18:36:36

我有以下视图(基本的"编辑"模板)

  @model SuccessStories.Models.Testimonials
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Testimonials</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)
        <div class="form-group">
            @Html.LabelFor(model => model.Testimonial, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Testimonial, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Testimonial, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

以下操作在我的控制器中产生:

[HttpGet]
    public ActionResult Edit(int id)
    {
            TestimonialsContext testContext = new TestimonialsContext();
            Testimonials testimonials = testContext.testimonialContext.Find(id);
            return View(testimonials);  
    }
    [HttpPost]
    public ActionResult Edit(Testimonials testimonial)
    {
        TestimonialsContext testContext = new TestimonialsContext();
        testContext.Entry(testimonial).State = EntityState.Modified;
        testContext.SaveChanges();
        return RedirectToAction("Index");
    }

错误位于此行:

testContext.Entry(testimonial).State = EntityState.Modified;

我得到的错误是"值不能为空。参数名称:实体

说明:执行当前 Web 请求期间发生未经处理的异常。请查看堆栈跟踪,了解有关错误及其在代码中起源位置的详细信息。

异常详细信息:System.ArgumentNullException:值不能为空。参数名称:实体"

请帮忙。我已经查找了这个,但找不到适合我的解决方案。谢谢!

值不能为空.参数名称:实体

谢谢大家的帮助。我想出了这个方法来修复它,基于你告诉我什么是空的。

        [HttpPost, ActionName("Edit")]
    public ActionResult EditConfirmed(int id, string Testimonial)
    {
        TestimonialsContext testContext = new TestimonialsContext();
        Testimonials testimonial = testContext.testimonialContext.Find(id);
        testimonial.Testimonial = Testimonial;
        testContext.Entry(testimonial).State = EntityState.Modified;
        testContext.SaveChanges();
        return RedirectToAction("Index");
    }

推荐是输入框的名称,它与数据库表中的条目同名。