2014-11-26 4 views
2

DB에 저장하기 위해 다시 게시하려고하는 ViewModel이 있습니다. ViewModel이 //GET Create(int id)에 설정된 값을 얻는 동안 //POST Create()에 도착할 때까지 일부가 손실됩니다. GoalLevelGoalTitle이 확인을 통과하지만 ActorIdProjectId이 손실되고 디버거가 if (Model.State.IsValid) 블록을 통과하고 있어도 통과 할 값이 DB에 저장되지 않습니다. 더 이상 유효한 ProjectId을 URL에 전달하지 않아 리디렉션이 실패합니다.POST 작업에서 모델 값이 손실되는 이유는 무엇입니까?

내가하는 일을 아는 것이 분명 할 것입니다.

CONTROLLER

// GET: UseCases/Create 

    public ActionResult Create(int id) 

    { 

     ViewBag.projectId = id; 

     //Populate the ViewModel 
     UserGoalsStepViewModel model = new UserGoalsStepViewModel() 
     { 
      ProjectId = id, 
      ActorList = new SelectList(db.Actors.Where(a => a.projectID == id), "id", "Title"), 

     }; 

     return View(model); 
    } 

    // POST: UseCases/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 ActionResult Create([Bind(Include = "ProjectId,ActorId,GoalTitle,Level")] UserGoalsStepViewModel model) 
    { 




     if (ModelState.IsValid) 
     { 

      //Create a use case object to map to, which can then be saved in the DB 

      UseCase uc = new UseCase(); 
      uc.ProjectID = model.ProjectId; 
      uc.ActorID = model.ActorId; 
      uc.Level = (Level)model.Level; 
      db.SaveChanges(); 
      return RedirectToAction("Index", new { id = model.ProjectId }); 
     } 

     return View(model); 
    }   

뷰 모델

public class UserGoalsStepViewModel 
    { 
     public enum GoalLevel 
     { 
      Summary, UserGoal, SubGoal, 
     } 

      public int ProjectId { get; set; } 
      public int ActorId { get; set; } 
      [DisplayName("Actor Title")]  
      public SelectList ActorList { get; set; } 
      [DisplayName("Goal Title")] 
      public string GoalTitle { get; set; } 
      public GoalLevel Level { get; set; } 

      public UserGoalsStepViewModel() 
      { 

      } 


    } 

VIEW

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 

    <div class="form-horizontal"> 
     <h4>UseCase</h4> 
     <hr /> 
     @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

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

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

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

     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="submit" value="Create" class="btn btn-default" /> 
      </div> 
     </div> 
    </div> 
} 

UPDA 아직 POST 오류가 발생하여 DB에 저장되지 않는 POST 메서드

수정 후 DB에 저장할 때이 오류 Message=The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.UseCase_dbo.Actor_ActorID". The conflict occurred in database "JustSpecIt", table "dbo.Actor", column 'ID'이 표시됩니다. 여기

는 업데이트 된 POST 방법의 관련 비트 :

if (ModelState.IsValid) 
      { 

       //Create a use case object to map to, which can then be saved in the DB 

       UseCase uc = new UseCase(); 
       uc.ProjectID = model.ProjectId; 
       uc.ActorID = model.ActorId; 
       uc.Title = model.GoalTitle; 
       uc.Level = (Level)model.Level; 
       db.UseCases.Add(uc); 
       db.SaveChanges(); 
       return RedirectToAction("Index", new { id = model.ProjectId }); 
      } 

답변

5

당신은 그들에게 다시 전송 게시 된 값에 포함 할 수 있도록 양식에 숨겨진 입력으로 ProjectId 및 ActorId에 대한 값을 저장해야합니다 귀하의 컨트롤러 동작.

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 
    @Html.HiddenFor(x => x.ProjectId) 
    @Html.HiddenFor(x => x.ActorId) 
    ... 
} 
+0

감사합니다. 보기에 모델 값을 가지고있는 것이 없으면 게시 할 때 모델 값이 손실 될 수 있다는 것을 깨닫지 못했습니다. 여전히 데이터베이스에 저장하는 데 문제가 있습니다.이 예외가 발생합니다. ' 'Message = INSERT 문이 FOREIGN KEY 제약 조건 "FK_dbo.UseCase_dbo.Actor_ActorID"와 충돌합니다. 충돌은 데이터베이스 "JustSpecIt", 테이블 "dbo.Actor", 열 'ID''에서 발생했습니다. 위의 게시물에 대한 업데이트를 추가했습니다. – gazrolo4

+0

실제로 FK 오류가 발생하는 이유는 ActorId입니다. 여전히 게시되지 않습니다. 좀 더 조사하겠습니다. SelectList와 관련이 있다고 의심됩니다. – gazrolo4

+1

모델 속성의 이름이 ActorList이므로 ActorId라는 값을 액션에 전달하는 대신 액션을 전달하고 있습니다. 값은 ActorList입니다. – mreyeros

관련 문제