2017-09-15 15 views
1

면도날 뷰의 왼쪽에 약 5 개의 열이있는 직원 목록을 표시하고 직원 (행)을 선택하면 직원의 세부 정보를 읽기 전용 부분으로 표시합니다 오른쪽 이미지 - 아래 이미지와 같습니다. 레코드를 추가/업데이트하기 위해 나중에 다른 뷰에서 세부 정보 양식을 다시 사용하는 것이 바람직합니다. enter image description hereMVC PartialView에 모델 세부 정보가 입력되지 않았습니다.

내 컨트롤러는 다음과 같습니다 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace Mymvc.Controllers 
{ 
    public class EmpController : Controller 
    { 
     private readonly MyEntities _db = new MyEntities(); 
     private IEnumerable<vEmployee> _Employees; 

     // GET: Employee 
     public ActionResult Index() 
     { 
      ViewData["ModuleName"] = "Active Employees"; 
      ViewData["deptIDList"] = _db.lu_Department.OrderBy(e => e.Dept); 
      ViewData["jobTitleIDList"] = _db.lu_JobTitle.OrderBy(e => e.JobTitle); 
      ViewData["genderList"] = _db.lu_Gender.OrderBy(e => e.Gender); 
      ViewData["ethnicityList"] = _db.lu_Ethnicity.OrderBy(e => e.Ethnicity); 
      ViewData["nationalityList"] = _db.lu_Nationality.OrderBy(e => e.Nationality); 
      ViewData["staffLocationList"] = _db.lu_StaffLocation.OrderBy(e => e.StaffLocation); 
      ViewData["notchList"] = _db.lu_EmploymentGradeNotch.OrderBy(e => e.Notch); 
      ViewData["salutationList"] = _db.lu_Salutation.OrderBy(e => e.Title); 
      return View(); 
     } 

     public ActionResult EmployeeDetails(int employeeID = 0) 
     { 
      vEmployee SelectedEmployee = null; 
      ViewData["deptIDList"] = _db.lu_Department.OrderBy(e => e.Dept); 
      ViewData["jobTitleIDList"] = _db.lu_JobTitle.OrderBy(e => e.JobTitle); 
      ViewData["genderList"] = _db.lu_Gender.OrderBy(e => e.Gender); 
      ViewData["ethnicityList"] = _db.lu_Ethnicity.OrderBy(e => e.Ethnicity); 
      ViewData["nationalityList"] = _db.lu_Nationality.OrderBy(e => e.Nationality); 
      ViewData["staffLocationList"] = _db.lu_StaffLocation.OrderBy(e => e.StaffLocation); 
      ViewData["notchList"] = _db.lu_EmploymentGradeNotch.OrderBy(e => e.Notch); 
      ViewData["salutationList"] = _db.lu_Salutation.OrderBy(e => e.Title); 
      try 
      { 
       if (employeeID == 0) 
        employeeID = _db.Employees.OrderBy(m => m.EmployeeNumber).First().EmployeeID; 

       if (_Employees == null) 
        _Employees = GetEmployees(); 

       SelectedEmployee = _Employees.First(e => e.EmployeeID == employeeID); 

      } 
      catch (Exception e) 
      { 
       var msg = e.Message; 
      } 
      return View(SelectedEmployee); 
     } 

     private IEnumerable<vEmployee> GetEmployees() 
     { 
      IEnumerable<vEmployee> emp = (from e in _db.Employees 
              join c in _db.Contacts on e.EmployeeID equals c.EmployeeID 
              join g in _db.lu_EmploymentGradeNotch on e.NotchID equals g.NotchID 
              join u in _db.lu_Salutation on c.SalutationID equals u.TitleID into sal 
              from u in sal.DefaultIfEmpty() 
              join s in _db.lu_SUBDepartment on e.SubDeptID equals s.SubDeptID into sde 
              from s in sde.DefaultIfEmpty() 
              join l in _db.lu_StaffLocation on e.StaffLocationID equals l.StaffLocationID into cl 
              from cm in cl.DefaultIfEmpty() 
              join t in _db.lu_Ethnicity on c.EthnicityID equals t.EthnicityID into eth 
              from et in eth.DefaultIfEmpty() 
              join n in _db.lu_Nationality on c.NationalityID equals n.NationalityID into nt 
              from nt1 in nt.DefaultIfEmpty() 
              where c.ContactTypeID == 1 && e.EmploymentStatusID == 1 
              select new vEmployee 
              { 
               EmployeeID = e.EmployeeID, 
               EmployeeNumber = e.EmployeeNumber, 
               DeptID = e.DeptID, 
               SubDeptID = e.SubDeptID, 
               JobTitleID = e.JobTitleID, 
               ReportsToID = e.ReportsToID, 
               NotchID = g.NotchID, 
               HireDate = e.HireDate, 
               StaffLocationID = e.StaffLocationID, 
               FirstName = c.FirstName, 
               LastName = c.LastName, 
               MiddleName = c.MiddleName, 
               FullName = c.FirstName + (c.MiddleName == null ? "" : " " + c.MiddleName) + " " + c.LastName + " (" + u.Title + ")", 
               SalutationID = c.SalutationID, 
               GenderID = c.GenderID, 
               EthnicityID = c.EthnicityID, 
               NationalityID = c.NationalityID, 
               Photograph = e.Photograph 
              }) 
        .AsEnumerable() 
        .OrderBy(m => m.EmployeeNumber) 
        .ThenBy(m => m.FirstName); 

      return emp; 
     } 
     public ActionResult ActiveEmployees_Read([DataSourceRequest] DataSourceRequest request) 
     { 
      _Employees = GetEmployees(); 
      return Json(_Employees.ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet); 
     }  

    } 
} 

내 주요 인덱스보기 :

@using Mymvc.Models 
@model Mymvc.Models.vEmployee 
@using System.Collections 

<div class="col col-xs-6"> 
     @(Html.Kendo().Grid<vEmployee>() 
     .Name("EmployeesList") 
     .Columns(columns => 
     { 
      columns.Bound(p => p.EmployeeNumber).Width(35); 
      columns.Bound(p => p.FirstName).Width(60); 
      columns.Bound(p => p.LastName).Width(60); 
      columns.ForeignKey(p => p.JobTitleID, (IEnumerable)ViewData["jobTitleIDList"], "JobTitleID", "JobTitle") 
        .Width(60); 
      columns.ForeignKey(p => p.DeptID, (IEnumerable)ViewData["deptIDList"], "DeptID", "Dept") 
        .Width(60); 
     }) 
     .Events(e => e.Change("Grid_OnRowSelect")) 
     .Events(e => e.DataBound("Grid_OnDataBound")) 
     .DataSource(dataSource => dataSource 
      .Ajax() 
      .PageSize(15) 
      .ServerOperation(false) 
      .Events(events => events.Error("grid_error")) // Handle the "error" event 
      .Model(model => 
      { 
       model.Id(m => m.EmployeeID); 
       model.Field(m => m.EmployeeID).Editable(false); 
      }) 
      .Read(read => read.Action("ActiveEmployees_Read", "Employee")) 
      ) 
      .Filterable() 
      .Pageable() 
      .Sortable() 
      .Selectable() 
     ) 
    </div> 

    @Html.Partial("_EmployeeDetails"); 

    <script type="text/javascript"> 
     Grid_OnDataBound = function (e) { 
      var grid = $("#EmployeesList").data("kendoGrid"); 
      grid.select(e.sender.tbody.find("tr:first")); 
     } 

     Grid_OnRowSelect = function (e) { 
      var data = this.dataItem(this.select()); 
      var empID = data.id;//IMP 
      $.ajax({ 
       url: '/Employee/EmployeeDetails', 
       type: "GET", 
       //dataType: "JSON", 
       data: { 'employeeID': empID } 
      }); 
     } 
    </script> 

내 목록에있는 모든 직원을 선택하면 내 OnDataBound 및 OnRowSelect 이벤트 내 EmployeeDetails 선택한 직원 ID를 전송 제어기 방법.

내 PartialView :

@model Mymvc.Models.vEmployee 
@using System.Collections 

<div class="col col-xs-6"> 
    @using (Html.BeginForm("EmployeeDetails", "Employee")) 
    { 
     <div class="container"> 

      <div class="col-md-8 well"> 
       <div class="form-horizontal"> 
        @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

        <div id="updateMsg" class="demo-section k-content"></div> 

        <div class="form-group"> 
         @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-3" }) 
         <div class="col-md-5"> 
          @Html.TextBoxFor(model => model.LastName, new { style = "width: 400px" }) 
          @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" }) 
         </div> 
        </div> 

        <div class="form-group"> 
         @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-3" }) 
         <div class="col-md-5"> 
          @Html.TextBoxFor(model => model.FirstName, new { style = "width: 400px" }) 
          @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" }) 
         </div> 
        </div> 

        <div class="form-group"> 
         @Html.LabelFor(model => model.MiddleName, htmlAttributes: new { @class = "control-label col-md-3" }) 
         <div class="col-md-5"> 
          @Html.TextBoxFor(model => model.MiddleName, new { style = "width: 400px" }) 
          @Html.ValidationMessageFor(model => model.MiddleName, "", new { @class = "text-danger" }) 
         </div> 
        </div> 

        <div class="form-group"> 
         @Html.LabelFor(model => model.SalutationID, htmlAttributes: new { @class = "control-label col-md-3" }) 
         <div class="col-md-2"> 
          @Html.DropDownListFor(model => model.SalutationID, new SelectList((IEnumerable)ViewData["salutationList"], "TitleID", "Title")) 
          @Html.ValidationMessageFor(model => model.SalutationID, "", new { @class = "text-danger" }) 
         </div> 

         @Html.LabelFor(model => model.GenderID, htmlAttributes: new { @class = "control-label col-md-2 col-md-offset-2" }) 
         <div class="col-md-1"> 
          @Html.DropDownListFor(model => model.GenderID, new SelectList((IEnumerable)ViewData["genderList"], "GenderID", "Gender")) 
          @Html.ValidationMessageFor(model => model.GenderID, "", new { @class = "text-danger" }) 
         </div> 
        </div> 

        <div class="form-group"> 
         @Html.LabelFor(model => model.NationalityID, htmlAttributes: new { @class = "control-label col-md-3" }) 
         <div class="col-md-1"> 
          @Html.DropDownListFor(model => model.NationalityID, new SelectList((IEnumerable)ViewData["nationalityList"], "NationalityID", "Nationality")) 
          @Html.ValidationMessageFor(model => model.NationalityID, "", new { @class = "text-danger" }) 
         </div> 
        </div> 

        <div class="form-group"> 
         @Html.LabelFor(model => model.EthnicityID, htmlAttributes: new { @class = "control-label col-md-3" }) 
         <div class="col-md-1"> 
          @Html.DropDownListFor(model => model.EthnicityID, new SelectList((IEnumerable)ViewData["ethnicityList"], "EthnicityID", "Ethnicity")) 
          @Html.ValidationMessageFor(model => model.EthnicityID, "", new { @class = "text-danger" }) 
         </div> 
        </div> 

        <div class="form-group"> 
         @Html.LabelFor(model => model.Photograph, htmlAttributes: new { @class = "control-label col-md-3" }) 
         <div class="col-md-5"> 
          @Html.TextBoxFor(model => model.Photograph, new { style = "width: 180px" }) 
          @Html.ValidationMessageFor(model => model.Photograph, "", new { @class = "text-danger" }) 
         </div> 
        </div> 
       </div> 

       <style> 
        .demo-section { 
         text-align: center; 
         line-height: 4em; 
        } 
       </style> 
      </div> 
     </div> 
    } 

</div> 

내 과제 :

내 세부 왼쪽 목록에 직원 선택에 모델 정보와 partialview 채울 수 없습니다. 디버그에서 EmployeeDetails 메서드의 SelectedEmployee 개체를 볼 때 세부 정보 (성, 이름 등)를 볼 수 있습니다. 내 Ajax 메서드가 제대로 작동하는지 확인합니다.

내가 뭘 잘못하고 있니? 또한 mvc에서 동일한 뷰에 목록 및 세부 정보를 표시하는 더 나은 방법이 있습니까?

감사합니다.

+0

대신 부분 렌더링 렌더링 동작을 사용하십시오. – bilpor

+0

@ Html.Partial ("_ EmployeeDetails", Model)에 모델을 전달합니다. 그것은 모델을 받아들이 기 때문입니다. – TechGirl

답변

0

@Html.Partial("_EmployeeDetails")은 _EmployeeDetails 뷰만 호출합니다. 이 코드는 Controller_EmployeeDetails 메서드를 호출 할 수 없습니다.

그래서, 당신이 필요로 @Html.Action("_EmployeeDetails");

_EmployeeDetails 조치에 컨트롤러

변경 @Html.Partial("_EmployeeDetails")를 통해보기에 액세스 이드 매개 변수를 선택 걸릴 수 있습니다.

@Html.Action("_EmployeeDetails", new { id = yourSelectedRowIdValue }) 

선택한 ID를 찾아 _EmployeeDetails 메소드 세부 정보 데이터에서 찾을 수 있습니다.

public ActionResult _EmployeeDetails (int id) 
     { 
      // var employeeDetail = find _EmployeeDetail using by id     
      return View (employeeDetail); 
     } 
+0

모델을 사용하면 'model'이라는 이름이 제공됩니다.보기 및 부분보기 모두에 @model myMvc.Models.vEmployee가 있어도 현재 컨텍스트에 존재하지 않습니다. – user938455

+0

제안이 효과가 없습니다. view 및 partialview 모두 @model myMvc.Models.vEmployee 문을 가지고 있더라도 모델을 사용하면 "name '모델이'현재 컨텍스트에 존재하지 않습니다. '라는 오류가 발생합니다. @ Html.Action ("EmployeeDetails")을 사용하면 여전히 채워지지 않은 세부 정보 partialview가 생성됩니다. BTW, 메서드 EmployeeDetails 및 부분 뷰 _EmployeeDetails – user938455

+0

나는 당신의 문제에 대한 답변을 업데이 트합니다. 시나리오에 따라 편집해야하는 올바른 방법입니다. –