【问题标题】:Edit in mvc4 didn't work在 mvc4 中编辑不起作用
【发布时间】:2017-01-19 03:11:37
【问题描述】:

我想在数据库中编辑这些数据并返回新数据
当我点击保存按钮数据没有改变 这是控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(CustomPerformancePerformersModel customPerformancePerformersModel)
    {
        if (ModelState.IsValid)
        {
            int perfromanceId = Convert.ToInt32(TempData.Peek("CurrentPerformanceId"));
            customPerformancePerformersModel.performanceObj = db.Performances.Where(x => x.PerformanceId == perfromanceId).FirstOrDefault();
            db.Entry(customPerformancePerformersModel.performanceObj).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.EventId = new SelectList(db.Events, "EventId", "Name", customPerformancePerformersModel.performanceObj.EventId);
        ViewBag.VenueId = new SelectList(db.Venues, "VenueId", "Name", customPerformancePerformersModel.performanceObj.VenueId);
        ViewBag.Performers = new SelectList(db.PerformerPerformances, "Performers", "Name", customPerformancePerformersModel.performanceObj.PerformerPerformances);
        return View(customPerformancePerformersModel.performanceObj);
    }

这里是html:

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

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

【问题讨论】:

  • 是否调用了您的编辑操作?
  • 能否粘贴整个表单 html 以及提交按钮和相关的 javascript(如果有)?你的编辑操作有断点吗?
  • 我猜想通过执行 customPerformancePerformersModel.performanceObj = db.Performances.Where(x => x.PerformanceId == perfromanceId).FirstOrDefault();您正在覆盖对模型的任何更改。所以在保存已经存在的东西。而是像您已经做的那样从数据库中获取性能,但是到一个局部变量中。然后用 CustomerPerformanceModel 中的数据更改它的数据,然后保存该局部变量
  • customPerformancePerformersModel.performanceObj = db.Performances.Where(x =&gt; x.PerformanceId == perfromanceId).FirstOrDefault(); 正在从数据库中获取对象。这将覆盖 performanceObj 中在编辑表单中提交的任何值。
  • @amalmansour 不要删除链接声明。但不是将语句的值设置为 customPerformancePerformersModel.performanceObj,而是将其设置为一个新变量。 var performance = db.Performances.Where(x =&gt; x.PerformanceId == perfromanceId).FirstOrDefault(); 然后在性能变量中设置 customPerformancePerformersModel.performanceObj 的值。然后只需保存更改,它应该可以工作

标签: c# html asp.net-mvc-4


【解决方案1】:

尝试以下方法:

    if (ModelState.IsValid)
    {
        int perfromanceId = Convert.ToInt32(TempData.Peek("CurrentPerformanceId"));

        // There is no need to use Where. FirstOrDefault has an overload using predicates.
        var savedPerformance = db.Performances.FirstOrDefault(x => x.PerformanceId == perfromanceId); 

        // If the performance couldn't be found, then you could add the error to the model state and return it to the view.
        if(savedPerformance == null)
            return View(customPerformancePerformersModel.performanceObj);

        // Update properties from performance in database with new performance.
        savedPerformance.someProperty = customPerformancePerformersModel.performanceObj.someProperty;

        db.Performances.Attach(savedPerformance);
        db.Entry(savedPerformance ).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }

【讨论】:

  • 这部分对我来说没有意义 savedPerformance = customPerformancePerformersModel.performanceObj; 因为你在该行之前设置它然后你在这里再次设置它。
  • @amalmansour 如果 savedPerformance 返回 null,则表示在数据库中没有找到它。您应该检查 perfromanceId 是否具有正确的值。 KSib 你是对的。我想按属性设置属性。我会更新
【解决方案2】:

理想情况下,您的代码应如下所示:

public ActionResult Edit(int performanceId)
{
    var model = db.Performances.FirstOrDefault(m => m.PerformanceId == performanceId);
    return View(model);
}

[HttpPost] //[HttpPatch] is technically correct, but most people I see tend to use only GET and POST actions.
[ValidateAntiForgeryToken]
public ActionResult Edit(CustomPerformancePerformersModel model)
{
    if (ModelState.IsValid)
    {
        db.Entry(model).State = EntityState.Modified;
        db.SaveChanges();
    }
}

您正在从数据库中检索对象并在您的 GET 操作中对其进行跟踪,使用您的表单对其进行修改,然后在您的更新操作中将其标记为已修改。如果您使用的是 MVC 模式,这是严格的,如果您使用单独的数据和视图模型,它看起来会有所不同(见下文)。如果您的视图没有模型上所有属性的字段(隐藏或不隐藏),您可能会在使用这种方法时遇到问题。

使用单独的数据和视图模型,你会得到这样的:

public ActionResult Edit(int performanceId)
{
    var performance = db.Performances.FirstOrDefault(m => m.PerformanceId == performanceId);
    var model = new PerformanceViewModel(performance); //In this constructor, copy properties from your data model to your view model
    return View(model);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PerformanceViewModel model)
{
    var performance = db.Performances.FirstOrDefault(m => m.PerformanceId == model.PerformanceId);
    model.Update(performance);
    db.SaveChanges();

}

使用示例视图模型:

public class PerformanceViewModel
{

    public PerformanceViewModel(CustomPerformanceePerformersModel model)
    {
        PerformanceId = model.performanceObj.PerformanceId;
        IsVisible = model.performanceObj.IsVisible;
        IsFeatured = model.performanceObj.IsFeatured;
    }
    public int PerformanceId { get; set; }

    public bool IsVisible { get; set; }

    public bool IsFeatured { get; set; }


    public void Update(CustomPerformancePerformersModel model)
    {
        model.performanceObj.IsVisible = IsVisible;
        model.performanceObj.IsFeatured = IsFeatured;
    }
}

在这里,您将创建一个单独的对象(视图模型),该对象仅包含您的视图所需的数据,然后使用来自该对象的数据来更新您的数据模型。我更喜欢这个,因为它能够有效地直接修改数据库,而且你可以在 Update(Model) 方法中进行任何必要的中间处理(将字符串转换为布尔值等)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2013-08-18
    • 2014-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多