2016-12-22 2 views
0

잠시 동안 뷰 모델에 문제가있어서 뭔가 정리하고 싶습니다. 내 뷰 모델에서는 "색인"을 표시 할 수 있으며 새 직원 "만들기"를 추가 할 수 있지만 "편집"이 작동하지 않습니다.MVC viewmodel Httppost 이후에 아무것도 표시되지 않습니다.

"수정"페이지를 표시하고 이름을 변경하는 것과 같은 편집 작업을 수행하지만 다시 게시하면 모든 데이터가 null으로 표시됩니다. "작성"에서 삽입을 게시 한 후 컨트롤러는 변경 사항 (EmployeeViewModel)을 표시하고 레코드를 삽입합니다. "편집"을 할 때 표시되지 않습니다.

viewmodel에는 고유 한 것이 있습니까? 아니면 다른 것이 있습니까?

다음
public partial class Employee 
    { 
     public int EmployeeId { get; set; } 
     public string Name { get; set; } 
     public Nullable<int> DepartmentId { get; set; } 
     public string Address { get; set; } 

     public virtual Department Department { get; set; } 
    } 

public partial class Department 
    { 
     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] 
     public Department() 
     { 
      this.Employees = new HashSet<Employee>(); 
     } 

     public int DepartmentId { get; set; } 
     public string DepartmentName { get; set; } 

     [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] 
     public virtual ICollection<Employee> Employees { get; set; } 
    } 

    public class EmployeeViewModel 
    { 
     public int EmployeeId { get; set; } 
     public string Name { get; set; } 
     public Nullable<int> DepartmentId { get; set; } 
     public string Address { get; set; } 
     public string DepartmentName { get; set; } 

    } 

내 컨트롤러 :

public class TestController : Controller 
    { 
     public db dContext = new db(); 
     public ActionResult Index() 
     { 
      List<Employee> employeelist = dContext.Employees.ToList(); 
      EmployeeViewModel employeeVM = new EmployeeViewModel(); 

      List<EmployeeViewModel> employeeVMList = employeelist.Select(x => new EmployeeViewModel 
      { 
       Name = x.Name, 
       EmployeeId = x.EmployeeId, 
       Address = x.Address, 
       DepartmentId = x.DepartmentId, 
       DepartmentName = x.Department.DepartmentName 
      }).ToList(); 
      return View(employeeVMList);  
     } 
     public ActionResult Create() 
     { 
      return View(); 
     } 
     [HttpPost] 
     [ValidateAntiForgeryToken] 
     public ActionResult Create(EmployeeViewModel employeeVM) 
     { 
      if (ModelState.IsValid) 
      { 
       Employee e = new Employee(); 
       e.EmployeeId = employeeVM.EmployeeId; 
       e.Name = employeeVM.Name; 
       e.DepartmentId = employeeVM.DepartmentId; 
       e.Address = employeeVM.Address; 

       dContext.Employees.Add(e); 
       dContext.SaveChanges(); 

       return RedirectToAction("Index"); 
      } 
      return View("Index"); 
     } 

     public ActionResult Edit(EmployeeViewModel em , int? id) 
     { 
      var dbEmpVM = (from e in dContext.Employees 
          join d in dContext.Departments 
          on e.DepartmentId equals d.DepartmentId 
          where e.EmployeeId == id 
          select new EmployeeViewModel 
          { 
           EmployeeId = e.EmployeeId, 
           DepartmentId=e.DepartmentId, 
           Address=e.Address, 
           Name=e.Name, 
           DepartmentName=d.DepartmentName 
          }).ToList();  
      return View(dbEmpVM ); 
     } 

     [HttpPost] 
     [ValidateAntiForgeryToken] 
     public ActionResult Edit(EmployeeViewModel model, int id) 
     { 
      string name = Request.Form["EmployeeId"]; 
      string naaanm = model.EmployeeId.ToString(); 

      return RedirectToAction("Index"); 
     } 
    } 

그리고 여기 내 편집의 :

여기 내 뷰 모델 클래스 (첫 번째 데이터베이스)의

@model IEnumerable<MVCTutorial.Models.EmployeeViewModel> 
@{ 
    ViewBag.Title = "Edit"; 
} 
<h4>(EmployeeViewModel)</h4> 
@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 

    foreach (var item in Model) 
    { 
<div class="form-group"> 
    @Html.LabelFor(i => item.EmployeeId, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EditorFor(i => item.EmployeeId, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(i => item.EmployeeId, "", new { @class = "text-danger" }) 
    </div> 
</div> 
<div class="form-group"> 
    @Html.LabelFor(i => item.Name, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EditorFor(i => item.Name, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(i => item.Name, "", new { @class = "text-danger" }) 
    </div> 
</div> 
<div class="form-group"> 
    @Html.LabelFor(i => item.DepartmentId, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EditorFor(i => item.DepartmentId, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(i => item.DepartmentId, "", new { @class = "text-danger" }) 
    </div> 
</div> 
     <div class="form-group"> 
      @Html.LabelFor(i => item.DepartmentName, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(i => item.DepartmentName, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(i => item.DepartmentName, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
     <div class="form-group"> 
      @Html.LabelFor(i => item.Address, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(i => item.Address, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(i => item.Address, "", new { @class = "text-danger" }) 
      </div> 
     </div> 
    } 
<div class="form-group"> 
    <div class="col-md-offset-2 col-md-10"> 
     <input type="submit" value="Edit" class="btn btn-default" /> 
    </div> 
</div> 
} 
<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

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

EmployeeViewModel

답변

0

귀하 현재 코드 (편집보기에서)는 아래와 같이 입력 마크 업을 생성합니다.

<input class="form-control text-box single-line" 
     id="item_DepartmentName" name="item.DepartmentName" type="text" value="SomeName" /> 

name 속성 값을 참조하십시오. "item.DepartmentName"입니다. HttpPost 작업 메서드 매개 변수는이 이름의 속성이없는 EmployeeViewModel 형식입니다. 따라서 모델 바인더는이 이름 ("item.DepartmentName")을 사용하여 양식에서 게시 된 양식 데이터를 메소드 매개 변수의 모든 특성에 매핑 할 수 없습니다.

해결책은 입력란의 이름이 인 속성을 EmployeeViewModel의 속성 이름과 일치하도록 업데이트하는 것입니다. 이상적으로 코드는 아래와 같이 마크 업을 생성해야합니다.

<input name="DepartmentName" type="text" value="Some value" /> 

html 헬퍼를 호출 할 때 name 속성을 명시 적으로 지정할 수 있습니다. 양식을 제출할 때 예를 들어, Html.TextBoxFor 도우미

@Html.TextBoxFor(i => item.DepartmentName, 
           new { @class = "form-control", NAME = "DepartmentName" }) 

으로 이제 모델 바인더는 EmployeeViewModel 개체의 DepartmentName 속성이 양식 필드의 값을 매핑 할 수 있습니다.

+0

수주 감사합니다. 그래도 나는 여전히 길을 잃었다. DepartmentName은 나에게 잘 들립니다. 내가 놓친 다른 것이 있습니까? 다른 클래스 (Department)이기 때문에 "TextBoxFor".. "EditorFor"보다는 그것을 변경해야합니까? –

+0

사용자가 입력 할 필드를 입력하려면 'TextBoXFor' 헬퍼 메소드를 사용하십시오. – Shyju

+0

줄을 Html.TextBoxFor (i => item.DepartmentName, new {htmlAttributes = new {@class = "form-control"}})로 변경했습니다. 그것은 여전히 ​​null을 보여줍니다. 뭔가 다른 점이 있습니까? –