【问题标题】:MVC PartialView is not populated with model detailsMVC PartialView 未填充模型详细信息
【发布时间】:2017-09-15 09:58:48
【问题描述】:

我打算在我的剃刀视图左侧显示一个包含大约五列的员工列表,并在选择任何员工(行)时,将员工的详细信息显示为右侧的只读部分视图 - 就像在下图。我希望稍后在另一个视图中重用详细信息表单来添加/更新记录。

我的控制器如下图所示:

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 事件将所选的 EmployeeID 发送到我的 EmployeeDetails 控制器方法。

我的部分视图:

@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>

我的挑战:

我无法在左侧列表中选择员工时使用模型信息填充我的详细信息部分视图。当我在调试中查看 EmployeeDetails 方法中的 SelectedEmployee 对象时,可以看到详细信息(姓氏、名字等),确认我的 ajax 方法运行良好。

我在这里做错了什么?另外,是否有更好的方法在 mvc 的同一视图中呈现列表和详细信息?

谢谢!

【问题讨论】:

  • 而不是使用渲染部分尝试渲染操作。
  • 将模型传递给@Html.Partial("_EmployeeDetails", Model);因为它接受一个模型。

标签: c# razor model-binding asp.net-mvc-partialview


【解决方案1】:

@Html.Partial("_EmployeeDetails") 只调用 _EmployeeDetails 视图。这段代码不能调用Controller_EmployeeDetails方法。

所以,根据需要,通过控制器访问视图

@Html.Partial("_EmployeeDetails") 更改为@Html.Action("_EmployeeDetails");

_EmployeeDetails 动作可以带选定的Id参数。

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

可以从_EmployeeDetails方法中找到选中的id并返回具体的详细数据。

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

【讨论】:

  • 使用模型给出的名称“模型”在当前上下文中不存在,即使视图和部分视图都有 @model myMvc.Models.vEmployee
  • 这两个建议都不起作用。即使视图和部分视图都具有@model myMvc.Models.vEmployee 语句,使用模型也会出现错误“当前上下文中不存在名称‘模型’”。使用 @Html.Action("EmployeeDetails") 仍然会产生一个未填充的详细信息部分视图。顺便说一句,方法是 EmployeeDetails,部分视图是 _EmployeeDetails
  • 我更新了您问题的答案。这只是你必须根据你的场景编辑一些代码的正确方法
  • 仍然无法按预期进行更改。您能否详细说明其他修改?
猜你喜欢
  • 2013-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多