簡體   English   中英

ASP.NET MVC使用ViewModel創建,編輯和刪除

[英]ASP.NET MVC Create, Edit and Delete using ViewModel

無論出於何種原因,我都無法使用我創建的名為ModelEmployeeViewModel的ViewModel進行創建和編輯。 但是,我可以不用使用CreateEmployeeViewModel就可以創建和編輯很好,但被告知將主要模型用於CRUD是很不現實的。 但是我可以使用CreateEmployeeViewModel來檢索我的2個DropDownList標記的值,而不能創建或編輯。 以下是我當前的模型,視圖模型,控制器和視圖。

我只是弄清楚了為什么不能使用public IActionResult Create(Employee employee) Active Method public IActionResult Create(Employee employee)

員工模型:(位於“模型”文件夾中)

    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>

在您的Create方法中,您將發送到視圖CreateEmployeeViewModel,但是在您的HttpPost Create方法中,您將接受Employee模型而不是CreateEmployeeViewModel。 因此,一旦更改了post方法簽名以接受正確的CreateEmployeeViewModel,就可以簡單地將其映射回Employee模型。

獲取操作方法:

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校准View模型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM