简体   繁体   English

在 mvc4 中编辑不起作用

[英]Edit in mvc4 didn't work

I want to edit this data in database and return new data我想在数据库中编辑这些数据并返回新数据
when i click on save button data doesn't change Here is controller :当我点击保存按钮数据不会改变这里是控制器:

    [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);
    }

and here is the html:这是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>

Try the following:请尝试以下操作:

    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");
    }

Ideally your code will look something like the following:理想情况下,您的代码如下所示:

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();
    }
}

You're retrieving the object from the database and tracking it in your GET action, modifying it using your form, then marking it as modified in your update action.您正在从数据库中检索对象并在您的GET操作中跟踪它,使用您的表单修改它,然后在您的更新操作中将其标记为已修改。 This is strictly if you're using the MVC pattern, and will look different (see below) if you're using separate data and view models.如果您使用 MVC 模式,这是严格的,如果您使用单独的数据和视图模型,则看起来会有所不同(见下文)。 You'll likely run into trouble with this approach if your view doesn't have fields (hidden or not) for all properties on your model.如果您的视图没有针对模型上所有属性的字段(隐藏或不隐藏),则使用这种方法可能会遇到麻烦。

Using separate data and view models, you'd have something like this:使用单独的数据和视图模型,你会得到这样的东西:

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();

}

With a sample view model:使用示例视图模型:

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;
    }
}

Here you're creating a separate object (view model) that holds only the necessary data for your view, then using the data from that object to update your data model.在这里,您将创建一个单独的对象(视图模型),该对象仅包含您的视图所需的数据,然后使用来自该对象的数据来更新您的数据模型。 I prefer this because it takes the ability to effectively directly modify the database, and because you can do any necessary intermediate processing (casting strings to bools, et cetera) in the Update(Model) method.我更喜欢这个,因为它需要能够有效地直接修改数据库,并且因为您可以在 Update(Model) 方法中进行任何必要的中间处理(将字符串转换为 bool 等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM