c# – DropDownList项在发布到编辑表单时为null

前端之家收集整理的这篇文章主要介绍了c# – DropDownList项在发布到编辑表单时为null前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有一个编辑员工的页面.

这是我的视图模型:

public class Employeesviewmodel
{
    [HiddenInput(DisplayValue = false)]
    public int EmployeeId { get; set; }      

    [required(ErrorMessage = "Position is required")]
    [DisplayName("Position")]
    public int EmployeeTypeId { get; set; }

    [required(ErrorMessage = "Name is required")]
    [DisplayName("Name")]
    public string Name { get; set; }


    public IEnumerable<EmployeeType> EmployeeTypes { get; set; }
}

这是我的控制器:

public class EmployeesController : Controller
{
    public ActionResult Edit(int id)
    {
        //get employee from id
        var employee = GetEmployee(id);

        if (employee != null)
        {
            var viewmodel = new Employeesviewmodel
            {
                EmployeeId = employee.EmployeeID,EmployeeTypeId = employee.EmployeeTypeID,Name = employee.Name,EmployeeTypes = _adminRepository.GetAllEmployeeTypes(),};

            return View(viewmodel);
        }

        //if no employee exists for this id,redirect to the Create page and display a friendly message
        TempData["message"] = "No employee exists with an ID of " + id + ",you can create a new employee here.";
        return RedirectToAction("Create");
    }



    [HttpPost]
    public ActionResult Edit(Employeesviewmodel viewmodel)
    {
        //if editing an employee,fetch it; otherwise,create a new one
        Employee employee = GetEmployee(viewmodel.EmployeeId);
        TryUpdateModel(employee);

        if (ModelState.IsValid)
        {              
            SaveEmployee(employee);
            TempData["message"] = "Employee has been saved.";
            return RedirectToAction("Details",new { id = employee.EmployeeID });
        }
        return View(viewmodel);     // validation error,so redisplay same view
    }
}

我的编辑视图页面

<%@ Page Title="" Language="C#" MasterPageFile="/Admin.Master" Inherits="System.Web.Mvc.ViewPage<Employeesviewmodel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <h1>Edit Employee</h1>

    <% Html.EnableClientValidation(); %>
    <% using (Html.BeginForm("Edit","Employees",FormMethod.Post)) { %>

        <%: Html.HiddenFor(m => m.EmployeeId)%>

        <div class="editor-label"><%: Html.LabelFor(m => m.EmployeeTypeId) %></div>
        <div class="editor-field">
            <%= Html.DropDownListFor(m => m.EmployeeTypeId,new SelectList(Model.EmployeeTypes,"EmployeeTypeID","Position",Model.EmployeeTypeId),"- Select an Employee Type -")%>
            <%: Html.ValidationMessageFor(m => m.EmployeeTypeId)%>
        </div>

        <div class="editor-label"><%: Html.LabelFor(m => m.Name) %></div>
        <div class="editor-field">
            <%: Html.TextBoxFor(m => m.Name)%>
            <%: Html.ValidationMessageFor(m => m.Name)%>
        </div>

        <p>
            <input type="submit" value="Save" />
            <%: Html.ActionLink("Cancel","Index") %>
        </p>

    <% } %>

</asp:Content>

提交表单后,if(ModelState.IsValid)失败.它在返回View时尝试重新显示视图(viewmodel);被调用,我收到此错误消息:

值不能为空.

参数名称:items

<%= Html.DropDownListFor(m => m.EmployeeTypeId,“EmployeeTypeID”,“Position”,“ – 选择员工类型 – ”)%>

我不确定为什么会这样.当我导航到页面时,下拉列表正确加载,但在重新显示视图时则没有.

有谁知道这里发生了什么?

解决方法

您需要从存储库重新加载视图模型上的EmployeeTypes属性,然后在出现错误时重新显示视图.永远不会发布此属性,因此在POST操作中它将始终为null,并且在呈现视图时,帮助程序将引发异常:
[HttpPost]
public ActionResult Edit(Employeesviewmodel viewmodel)
{
    //if editing an employee,create a new one
    Employee employee = GetEmployee(viewmodel.EmployeeId);
    TryUpdateModel(employee);
    if (ModelState.IsValid)
    {              
        SaveEmployee(employee);
        TempData["message"] = "Employee has been saved.";
        return RedirectToAction("Details",new { id = employee.EmployeeID });
    }

    // Reload employee types from repository before redisplaying the view
    viewmodel.EmployeeTypes = _adminRepository.GetAllEmployeeTypes();

    // validation error,so redisplay same view
    return View(viewmodel);
}
原文链接:https://www.f2er.com/csharp/243140.html

猜你在找的C#相关文章