【问题标题】:i want to INSERT employee attendance into database [closed]我想将员工出勤率插入数据库[关闭]
【发布时间】:2015-07-29 05:18:48
【问题描述】:

我想将员工出勤插入到我有部门下拉列表的数据库中,在选择部门时,html 表中填充了所有 emp 代码、emp 名称和一个下拉列表,其中包含与所选部门相关的出勤状态(存在/缺席)和在提交时将其插入到数据库中,其中包含部门名称、员工代码、员工名称、mvc 中的状态

这是 TblEmpAttendance 模型

namespace SchoolManagementSystem.EFModel
{
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;

public partial class TblEmpAttendance
{
    public int Emp_Attendance_Id { get; set; }
    public string Session { get; set; }
    public int Emp_Type_Id { get; set; }
    public string Emp_Type { get; set; }
    public int Emp_Dept_Id { get; set; }
    public string Emp_Deptartment { get; set; }
    public System.DateTime Date { get; set; }
    public int Emp_Official_Id { get; set; }
    public string Emp_Code { get; set; }
    public string Emp_Name { get; set; }
    public int Status_Id { get; set; }
    public string Status { get; set; }

    [ScriptIgnore]
    public TblDepartment TblDepartment { get; set; }
    [ScriptIgnore]
    public TblEmployeeOfficialDetail TblEmployeeOfficialDetail { get; set; }
    [ScriptIgnore]
    public  TblEmployeeType TblEmployeeType { get; set; }
}

}

这是我的 EF 模型

@model SchoolManagementSystem.EFModel.TblEmpAttendance

@using (Html.BeginForm("InsertEmpAttendanceAction", "Employee", FormMethod.Post)) {

<div>
    <div class="form-group" style="width :50%; float:left; padding-right:10px">
        <label>SESSION</label> <br />
        <input type="text" class="form-control font" id="ses" name="ses" value="2015-2016" readonly>
    </div>
        <div class="form-group" style="width: 50%; float: right; padding-right: 10px">
            <label>DATE</label> <br />             
            <input type="text" class="form-control font" id="Date" name="Date" value="@Model.Date.ToShortDateString()">
        </div>
    </div>

<div>

    <div class="form-group" style="width :50%; float:left">
        <label>EMPLOYEE TYPE</label> <br />
       @foreach (var type in ViewBag.Type_IdList)
        {
            <input type="radio" name="type" value="@type.Value" style="font:bold 16px verdana" /> <label>@type.Text</label> <br />
        }
       </div>
    <div class="form-group" style="width :50%; float:right">
        <label>EMPLOYEE DEPARTMENT</label> <br />
        @Html.DropDownList("DDLDepartment", ViewBag.Department_IdList as SelectList,"--SELECT DEPARTMENT--", new { @class = "ddlfont" })
    </div>
</div>


<div id="original" hidden>
    @Html.DropDownList("DDLStatus", ViewBag.Status_IdList as SelectList, new {@class = "ddlfont" })
</div>

<div class="form-group font" id="attend">

    <table>
        <tr>
            <th>EMPLOYEE CODE</th>
            <th>EMPLOYEE NAME</th>
            <th>ATTENDANCE</th>                
        </tr>
         <tr>

          </tr>

    </table>
</div> 

我正在使用 jQuery 填充表格,并且已正确填充:

$(document).ready(function () {
        $("#DDLDepartment").click(function () {

        $("#Emp_Deptartment").val($("#DDLDepartment option:selected").text());
        $("#Emp_Dept_Id").val($("#DDLDepartment option:selected").val());

       $('#attend table tr:not(:first)').remove();
        var deptid = parseInt($('#DDLDepartment').val());
        console.log(deptid);
        if ($('#DDLDepartment').val() != "--SELECT DEPARTMENT--") {

            $.ajax({
                url: "@Url.Action("GetEMPDetails", "Employee")",
                type: "GET",
                data: { DeptId: deptid },
                dataType: "json",
                contentType: "application/json",
                processdata: true,
                success: function (data) {                      
                    var dropdown = $('#DDLStatus').clone();
                    $.each(data, function (i, empdetail) {
                        console.log(empdetail);
                        $('#attend table').append("<tr><td>" + empdetail.Employee_Code + "</td><td>" + empdetail.Employee_Name + "</td><td>" + "<span class='abc'></span>" + "</td></tr>");
                        $('.abc').html(dropdown);


                        //$("#Emp_Official_Id").val(empdetail.Employee_Official_Id);                            

                    });


                },

            });
        }
        else {
            alert(" PLEASE SELECT VALID DEPARTMENT ")
        }

});
});

在我的控制器中

public ActionResult InsertEmpAttendanceAction(TblEmpAttendance empattendanceobj, **ICollection<TblEmpAttendance> attendance**)// here i was stuck as it returns null
        {

}

【问题讨论】:

  • 欢迎来到stackoverflow。请阅读How to Ask
  • 你的代码在哪里,你卡在哪里了?
  • 现在帮我解决这个问题...
  • 您的生成表单控件具有name 属性,这些属性与您的模型完全没有关系,因此在您回发时不会绑定。至少您需要向您展示TblEmpAttendance 的模型以帮助您解决此问题(提示:您必须使用for 循环或自定义EditorTemplate,而不是foreach 循环并使用强烈生成您的html types html helpers)既然你声称你的脚本正在工作,你为什么要包含它(它与问题有什么关系)?
  • 好的,我删除了 foreach 循环并添加了 TblEmpAttendance

标签: jquery sql-server asp.net-mvc


【解决方案1】:

您当前没有创建任何与TblEmpAttendance 相关的表单控件,只是为您的表中的每一行创建一个&lt;select&gt; name="DDLStatus"(由于重复的id 属性,这也会生成无效的html)。处理此问题的简单方法是从您的 GetEMPDetails() 方法返回部分视图而不是 JsonResult

首先你需要定义代表你在视图中显示/编辑的视图模型(参考What is ViewModel in MVC?

public class EmployeeVM
{
  public int ID { get; set; }
  public sting Code { get; set; }
  public string Name { get; set; }
  [Required(ErrorMessage = "Please select the status")]
  public int StatusID { get; set; }
}
public class AttendanceVM
{
  [Display(Name = "Department")]
  [Required(ErrorMessage = "Please select a department")]
  public int DepartmentID { get; set; }
  public DateTime Date { get; set; }
  .... // add other properties, for example for employee type etc, but its unclear how these are used in the view
  public List<EmployeeVM> Employees { get; set; }
  public SelectList StatusList { get; set; }
  public SelectList DepartmentList { get; set; }
}

接下来为EmployeeVM 类型创建一个EditorTemplate。在/Views/Shared/EditorTemplates/EmployeeVM.cshtml

@model yourAssembly.EmployeeVM
<tr>
  <td>@Html.DisplayFor(m => m.Code)</td>
  <td>@Html.DisplayFor(m => m.Name)</td>
  <td>
    @Html.HiddenFor(m => m.ID)
    @Html.DropDownListFor(m => m.StatusID, (SelectList)ViewData["statuslist"], "-Please select-")
  </td>
</tr>

然后创建一个局部视图来显示选定的员工(比如_EmployeeDetails.cshtml

@model yourAssembly.AttendanceVM
@Html.EditorFor(m => m.Employees, new { statuslist = Model.StatusList })

主视图将是

@model yourAssembly.AttendanceVM
@using (Html.BeginForm())
{
  @Html.LabelFor(m => m.DepartmentID)
  @Html.DropDownListFor(m => m.DepartmentID, Model.DepartmentList, "-Please select-")
  @Html.ValidationMessageFor(m => m.DepartmentID)
  @Html.LabelFor(m => m.Date)
  @Html.TextBoxFor(m => m.Date, "{0:d}")
  @Html.ValidationMessageFor(m => m.Date)
  // .... controls for other properties
  <table>
    <thead>
      <tr>
        <th>Code</th>
        <th>Name</th>
        <th>Attendance</th>                
      </tr>
    </thead>
    <tbody id="employees">
    </tbody>
  </table>
}

并将您的脚本修改为

var url = '@Url.Action("GetEmployeeDetails", "Employee")';
var table = $('#employees');
var form = $('form');
$('#DepartmentID').change(function() {
  if (!$(this).val() {
    return;
  }
  $.get(url, { ID: $(this).val() }, function(data) {
    table.html(data);
    // Reparse the validator
    form.data('validator', null);
    $.validator.unobtrusive.parse(form);
  });
});

最后是你的控制器方法

public ActionResult Index()
{
  AttendanceVM model = new AttendanceVM();
  ... // populate SelectList's, set default values for properties etc.
  return View(model);
}
[HttpPost]
public ActionResult Index(AttendanceVM model)
{
  if (!ModelState.IsValid)
  {
    ... // repopulate SelectList's
    returnView (model);
  }
  // Get the employees data models from the database based on model.DepartmentID
  var employees = db.TblEmpAttendance.Where(e => e.Emp_Dept_Id == model.DepartmentID);
  // Update each one based on the view model data
  foreach (var item in Model.Employee)
  {
    var employee = employees.Where(e => e.Emp_Attendance_Id == item.ID).FirstOrDefault();
    employee.Status_Id = item.StatusID;
    ....
  }
  // save each data model and redirect
}
public PartialViewResult GetEmployeeDetails(int ID)
{
  AttendanceVM model = new AttendanceVM();
  ... // populate collection of employees based on the department ID
  ... // populate SelectList for StatusList
  return PartialView("_EmployeeDetails", model);
}

要了解为什么这会在您发布时绑定到您的模型,请查看它为控件生成的 html,例如员工的下拉列表将是

<select name="Employees[0].StatusID" ...>
<select name="Employees[1].StatusID" ...>
<select name="Employees[2].StatusID" ...>

name 属性与您的模型无关 - 您的模型包含一个名为 Employees 的集合属性,每个员工(由索引定义)都有一个名为 StatusID 的属性

旁注:我强烈建议您的类和属性名称遵循常规约定

【讨论】:

  • 非常感谢,这真的很有帮助,我是 mvc 新手并正在尝试学习 mvc。
猜你喜欢
  • 2011-01-27
  • 1970-01-01
  • 2012-08-21
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
  • 2013-07-02
  • 2014-02-25
相关资源
最近更新 更多