ASP.NET MVC使用ViewModel创建,编辑和删除

时间:2016-07-11 16:36:38

标签: c# asp.net asp.net-mvc entity-framework

无论出于何种原因,我无法使用我创建的名为CreateEmployeeViewModel的ViewModel进行创建和编辑。然而,我可以在不使用CreateEmployeeViewModel的情况下创建和编辑,但被告知使用CRUD的主要模型是不好的。然而,我可以使用CreateEmployeeViewModel检索我的2个DropDownList标签的值,而不是创建或编辑。以下是我当前的模型,ViewModel,控制器和视图。

我只是弄清楚为什么我无法使用public IActionResult Create(Employee employee)主动方法创建。

员工模型:(位于Models文件夹中)

    public class Employee
{
    [Key]
    public int EmpId { get; set; }

    [Required]
    public string EmpFirstName { get; set; }

    [Required]
    public string EmpLastName { get; set; }

    public int DeptId { get; set; }
    public Department Department { get; set; }

    public int BldgId { get; set; }
    public Building Building { get; set; }
}

EmployeeController :(位于Controllers文件夹中)

public class EmployeeController : Controller
{
    private DataEntryContext _context;

    public EmployeeController(DataEntryContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        return View(_context.Employees.ToList());
    }

    // Populate Department values to DropDownList
    private IEnumerable<SelectListItem> GetDeptList()
    {
        var dept = _context.Departments
            .Select(s => new SelectListItem
            {
                Value = s.DeptId.ToString(),
                Text = s.DeptTitle
            })
            .ToList();

        return (dept);
    }

    // Populate Building values to DropDownList
    private IEnumerable<SelectListItem> GetBldgList()
    {
        var bldg = _context.Buildings
            .Select(b => new SelectListItem
            {
                Value = b.BldgId.ToString(),
                Text = b.BldgName
            })
            .ToList();

        return (bldg);
    }

    public IActionResult Create()
    {
        CreateEmployeeViewModel model = new CreateEmployeeViewModel();

        model.DeptList = GetDeptList();
        model.BldgList = GetBldgList();

        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Employee employee)
    {
        if (ModelState.IsValid)
        {
            _context.Employees.Add(employee);
            _context.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(employee);
    }

    public IActionResult Edit(int? id)
    {
        if (id == null)
        {
            return View("Error");
            //return NotFound();
        }

        var employee = _context.Employees
            .Where(e => e.EmpId == id)
            .Single();

        if (employee == null)
        {
            return View("Error");
            //return NotFound();
        }

        return View(employee);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Edit(Employee employee)
    {
        if (ModelState.IsValid)
        {
            _context.Employees.Update(employee);
            _context.SaveChanges();

           return RedirectToAction("Index");
        }

        return View(employee);
    }
}

CreateEmployeeViewModel :(位于ViewModels文件夹中)

    public class CreateEmployeeViewModel
{
    public int EmpId { get; set; }
    public string EmpFirstName { get; set; }
    public string EmpLastName { get; set; }


    public int DeptId { get; set; }
    public IEnumerable<SelectListItem> DeptList { get; set; }


    public int BldgId { get; set; }
    public IEnumerable<SelectListItem> BldgList { get; set; }
}

员工创建视图

<form asp-controller="employee" asp-action="Create" method="post" class="form-horizontal" role="form">
<div class="form-horizontal">
    <div asp-validation-summary="All" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="EmpFirstName" class="col-md-2 control-label">First Name</label>
        <div class="col-md-10">
            <input asp-for="EmpFirstName" class="form-control" />
            <span asp-validation-for="EmpFirstName" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="EmpLastName" class="col-md-2 control-label">Last Name</label>
        <div class="col-md-10">
            <input asp-for="EmpLastName" class="form-control" />
            <span asp-validation-for="EmpLastName" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="DeptId" class="col-md-2 control-label">Department</label>
        <div class="col-md-10">  
            <select asp-for="DeptId" asp-items="@Model.DeptList" class="form-control">
                <option>Select Department</option>
            </select>
            <span asp-validation-for="DeptId" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="BldgId" class="col-md-2 control-label">Building Location</label>
        <div class="col-md-10">
            <select asp-for="BldgId" asp-items="@Model.BldgList" class="form-control">
                <option>Select Building</option>
            </select>
            <span asp-validation-for="BldgId" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

2 个答案:

答案 0 :(得分:1)

在Create方法中,您要向视图发送CreateEmployeeViewModel,但在HttpPost Create方法中,您接受的是Employee模型而不是CreateEmployeeViewModel。因此,一旦您更改post方法签名以接受正确的CreateEmployeeViewModel,您只需将其映射回Employee模型即可。

答案 1 :(得分:0)

获取行动方法:

public IActionResult Create(Employee employee)
{
    return View(employee);
}

只需更改Post Action Method

即可
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(CreateEmployeeViewModel vm)
{
    if (ModelState.IsValid)
    {

var model = new Employee{
   //your logic here for example
    employeename = vm.employeename,
    employeepassword = vm.employeepassword
   } 
        _context.Employees.Add(model);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(employee);
}

并且不要忘记在.cshtml

中调用视图模型