我想INSERT员工出勤到数据库

时间:2015-07-29 05:18:49

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

我希望员工出勤进入数据库,我有一个部门下拉列表和部门选择,html表中填写了所有的emp代码,emp名称和一个与所选部门相关的出勤状态(现在/缺席)的下拉列表在提交时,它将插入数据库中,包含部门名称,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
        {

}

1 个答案:

答案 0 :(得分:0)

您目前没有创建与TblEmpAttendance相关的任何表单控件,只有<select>表示您name="DDLStatus"表中的每一行(由于重复{而生成无效的html} {1}}属性)。处理此问题的简便方法是从id方法返回部分视图而不是JsonResult

首先,您需要先定义视图模型,以表示您在视图中显示/编辑的内容(请参阅What is ViewModel in MVC?

GetEMPDetails()

接下来为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; } } 类型创建EditorTemplate。在EmployeeVM

/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);
  });
});

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

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);
}

<select name="Employees[0].StatusID" ...> <select name="Employees[1].StatusID" ...> <select name="Employees[2].StatusID" ...> 属性与您的模型无关 - 您的模型包含名为name的集合属性,每个员工(由索引定义)都有一个名为Employees的属性

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