微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在mvc

如何解决无法在mvc

这是我的问题,所以我只希望允许用户仅更改/编辑其密码和用户名
我给客户的原始模型是这个

public string IC { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username{ get; set; }
public string Password{ get; set; }

这是我的客户虚拟机

public string Username{ get; set; }
public string Password{ get; set; }

这是我的编辑功能控制器

public ActionResult Edit([Bind(Include = "Username,Password")] CustomersVM customersVM )
        {
            if (ModelState.IsValid)
            {
                db.Entry(customersVM ).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(customersVM );
        }

view.cshtml

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

因此,此虚拟机将使ModelState变为有效状态,该状态将直接进入数据库,但事实证明是发生了此类错误

system.invalidOperationException:'实体类型CustomerVM不是当前上下文模型的一部分。'

解决方法

为了编辑/更新记录,您需要首先识别该记录。就您而言,您的ViewModel不是数据库所拥有的,而是问题中的第一个模型。因此,您需要先将viewModel映射到真实模型,然后再保存或获取现有记录,然后对其进行修改,然后在保存之前将其设置为已修改。

public ActionResult Edit([Bind(Include = "Username,Password")] CustomersVM customersVM )
        {
            if (ModelState.IsValid)
            {
              var existing = db.Customers.FirstOrDefault(x => x.Id == customersVM.Id);
                if (existing != null)
                {
                     existing.Username  = customersVM.Username;
                     existing.Password = customerVM.Password;
                     db.Entry(existing ).State = EntityState.Modified;
                     db.SaveChanges();
                     return RedirectToAction("Index");
                }
            }
            return View(customersVM );
        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。