2

MVC5/EF6 응용 프로그램의 관리 섹션을 만들었습니다. 나는 성공적으로 Create() 및 Delete() 할 수 있지만 Edit()는 POST에서 계속 오류가 발생합니다.신원 사용자의 변경 사항을 저장할 수 없습니까?

보기 편집

@model PROJECT.Models.ApplicationUser 

@{ 
    ViewBag.Title = "Edit"; 
    Layout = "~/Areas/Admin/Views/Shared/_LayoutAdmin.cshtml"; 
    PROJECT.Helper.GeneralHelper helper = new PROJECT.Helper.GeneralHelper(); 
    string cancelEditUrl = "/Admin/UserManagement/"; 
} 

@using (Html.BeginForm("Edit", "UserManagement", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 
    @Html.HiddenFor(model => model.Id) 
    @Html.HiddenFor(model => model.ForumUsername) 
    @Html.HiddenFor(model => model.ReceiveSystemEmails) 
    @Html.HiddenFor(model => model.RegisteredDate) 
    @Html.HiddenFor(model => model.LastVisitDate) 

    <div class="container"> 
     <div class="row"> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.Name) 
      </div> 

      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.Name, new { @class = "form-control" }) 
       @Html.ValidationMessageFor(model => model.Name) 
      </div> 
     </div> 

     <div class="row"> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.Position) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.Position, new { @class = "form-control" }) 
       @Html.ValidationMessageFor(model => model.Position) 
      </div> 
     </div> 

     <div class="row"> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.Email) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.Email, new { @class = "form-control" }) 
       @Html.ValidationMessageFor(model => model.Email) 
      </div> 
     </div> 

     <div class="row"> 
      <div class="editor-label"> 
       @Html.LabelFor(model => model.PhoneNumber) 
      </div> 
      <div class="editor-field"> 
       @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "form-control", type = "tel" }) 
       @Html.ValidationMessageFor(model => model.PhoneNumber) 
      </div> 
     </div> 

     <div class="row"> 
      <div class="col-md-1" style="padding-left: 0px"> 
       <input type="submit" value="Save" class="btn btn-primary" /> 
      </div> 
      <div class="col-md-9" style="padding-left: 0px"> 
       <a href="@cancelEditUrl" class="btn btn-danger">Cancel</a> 
      </div> 

      @{ 
       string deleteURL = "/Admin/UserManagement/Delete/" + Model.Id; 
      } 
      <a [email protected] class="btn btn-danger col-md-2"> 
       <span class="glyphicon glyphicon-minus"></span> Delete User 
      </a> 
     </div> 
    </div> 
} 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

컨트롤러 : 나는 사용자를 만들 때

// GET: Admin/UserManagement/Edit/5 
    public async Task<ActionResult> Edit(string id) 
    { 
     if (id == null) 
     { 
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
     } 
     ApplicationUser model = await UserManager.FindByIdAsync(id); 
     if (model == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(model); 
    } 

    // POST: Admin/UserManagement/Edit/5 
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Edit([Bind(Include = "Id,property1, property2, etc...")] ApplicationUser applicationUser) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Entry(applicationUser).State = EntityState.Modified; 
      await db.SaveChangesAsync(); 
      return RedirectToAction("Index"); 
     } 
     return View(applicationUser); 
    } 

, 내가 입력해야하는 것은, 같은 Test User은 GUI 측에 Name & Email입니다 및 [email protected]. 사용자가 생성되면 내 새 사용자 편집을 선택할 수있는 내 색인보기로 돌아갑니다.

protected override void Dispose(bool disposing) 
    { 
     if (disposing) 
     { 
      db.Dispose(); 
     } 
     base.Dispose(disposing); 
    } 

내가 계속 : 다음 내보기 편집 열고 경우 나의 컨트롤러의 POST 편집() 코드를 실행하지만 await db.SaveChangesAsync(); 즉시 내 DB의 처분() 아래로 이동, 저장 Test Monkey 말의 위치를 ​​추가 클릭

Server Error in '/' Application. 

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. 

다른 사람이 갈 수 있습니다 무엇에 대한 아이디어가 : 거기에 나는 다음과 같은 오류 정보를 얻을 수에서? 이것은 이전에 MVC4/EF5에서 개발 된 프로젝트의 기능 섹션이었고 ID와 같은 MVC5의 향상된 기능을 사용하도록 업그레이드되었습니다.

편집 : 데이비드 마틴에 의해 제안

는 응용 프로그램의 추적을 구현 :

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

View ASP.Net Trace Information Application Trace

그게 아니라면 내가 지금 찾고 있어요 무엇인지 확신?

EDIT2 : 아직도

내가 정확히 추적에 후 해요,하지만 난 [DBEX]로 드릴 다운 캐치 내 중단 점을 사용하고 진정한 오류 메시지가 "사용자 이름 했다 찾았는지 확실하지 필드가 필요합니다 ". 내가 편집하고 지금 내 사용자에 대한 변경 사항을 저장 할 수 있어요 (내 현재 응용 프로그램에서 같은 일이다) applicationUser.UserName = applicaitonUser.Email을 추가함으로써

dbException

.

그러나 내가 알아낼 수없는 것, 이것이 처음부터 필요한 이유입니다. (내가 확인했다) 아래에서 알 수있는 바와 같이, 사용자의 [사용자 이름] 값이() 메소드 만들기 내 POST 내에서 설정 : 내 POST 편집에 필요한 따라서

// POST: Admin/UserManagement/Create 
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public async Task<ActionResult> Create([Bind(Include = "Id,property1,property2,etc.,UserName")] ApplicationUser applicationUser) 
    { 
     if ((applicationUser.MemberOrgId == null) && (applicationUser.SponsorOrgId == null)) 
     { 
      ModelState.AddModelError("", "Must select either an Organization or Sponsor from the dropdown lists."); 
      return View(applicationUser); 
     } 

     if (ModelState.IsValid) 
     { 
      ViewBag.headerTitle = "Create User"; 
      applicationUser.UserName = applicationUser.Email; 
      IdentityResult result = await UserManager.CreateAsync(applicationUser, "test12345"); 
      if (result.Succeeded) 
      { 
       await db.SaveChangesAsync(); 
       return RedirectToAction("Index", "UserManagement"); 
      } 
      else 
      { 
       ModelState.AddModelError("", "Failed to Create User."); 
       var errors = string.Join(",", result.Errors); 
       ModelState.AddModelError("", errors); 
      } 
     } 

     ModelState.AddModelError("", "Failed to Create User."); 
     var errors1 = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToString(); 
     ModelState.AddModelError("", errors1); 

     ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name", applicationUser.MemberOrgId); 
     ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name", applicationUser.SponsorOrgId); 
     if (applicationUser.MemberOrgId != null) 
     { 
      ViewBag.SwitchState = true; 
     } 
     else 
     { 
      ViewBag.SwitchState = false; 
     } 
     ViewBag.OrganizationId = new SelectList(db.MemberOrganizations, "Id", "State", applicationUser.MemberOrgId); 

     // If we got this far, something failed, redisplay form 
     return View(applicationUser); 
    } 

을, 그것은) (플래그해서는 안 그것은 이미 설정 되었기 때문에?

+0

디버그에서 실행할 수 있고 throw되는 예외를 잡을 수 있습니까? – Pseudonym

+2

EntityValidationErrors 속성을 확인 했습니까? 대답은 거기에 있습니다. – ozz

+0

@ PseudoNym01 필자는 POST 편집 메쏘드에 try-catch를 추가했다 :'return Json (new {error = ex.Message + ", \ n"+ ex.InnerException + ", \ n"+ ex.Data + ", 하나 이상의 엔터티에 대한 유효성 검사가 실패했습니다. 자세한 내용은 \ u0027EntityValidationErrors \ u0027 속성을 참조하십시오. \ n, \ nSystem.Collections.ListDictionaryInternal, \ n " nEntityFramework "}'. 그게 도움이 되니? @Ozz 나는 특정 속성을 확인하는 방법을 알아 내려고했지만 아직 행운을 찾지 못했습니다. –

답변

0

내가 실수 한 경우 확실하지 않지만 View의 UserName을 모델링으로 유지하지 않는 것 같습니다 (예 :@Html.HiddenFor(x=>x.UserName)을 사용하여 applicationUser.UserName = applicationUser.Email;의 UserName이 이후 으로 설정되어 있고 POST 작업에서 if (ModelState.IsValid)을 확인한 것 같습니다.

관련 문제