简体   繁体   中英

ASP.NET MVC Create, Edit and Delete using ViewModel

For whatever reason I'm unable to Create and Edit using the ViewModel called CreateEmployeeViewModel that I created. I can however Create and Edit fine without using the CreateEmployeeViewModel but was told it was bad practive to use the main Models for CRUD. I am however able to retrieve values to my 2 DropDownList tags fine using the CreateEmployeeViewModel, just not Create or Edit. Below are my current Models, ViewModels, Controllers and Views.

I just figure out why I cannot Create using the public IActionResult Create(Employee employee) Active Method.

Employee Model: (located in Models folder)

    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: (located in Controllers folder)

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: (located in ViewModels Folder)

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

Employee Create View:

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

In your Create method, you are sending to the view the CreateEmployeeViewModel but in your HttpPost Create method you are accepting back the Employee model instead of the CreateEmployeeViewModel. So once you change the post methods signature to accept the correct CreateEmployeeViewModel, you can simply map it back to the Employee model.

Get Action Method:

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

Just change in your 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);
}

and don´t forget to cal View Model in your .cshtml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM