ViewModel在HttpPost Edit上返回null

时间:2016-05-16 21:32:46

标签: asp.net asp.net-mvc viewmodel

我是MVC的新手并且正在学习它。我创建了两个名为Employees和Course的表,并使用实体框架创建了上下文类(DB first)。我使用metadatatype为两个模型类添加了验证对象,并创建了viewmodel以在视图上创建Radiobutton列表。我在Httppost编辑时为viewmodel对象获取null。

ViewModel cs

public class EmployeeCourseViewModel
{
    public Employee emp { get; set; }

    public List<Course> empCourse { get; set; }

    public int SelectDepartment { get; set; }


}

修改视图

@model WebApplication2.Models.EmployeeCourseViewModel
@using (Html.BeginForm("Edit", "Employee", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Employee</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.emp.EmpId)

        <div class="form-group">
            @Html.LabelFor(model => model.emp.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.emp.FirstName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.emp.FirstName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.emp.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.emp.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.emp.LastName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.emp.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.emp.Gender, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.emp.Gender, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.emp.EmailAddress, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.emp.EmailAddress, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.emp.EmailAddress, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.emp.PersonalWebSite, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.emp.PersonalWebSite, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.emp.PersonalWebSite, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.emp.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @*@Html.EditorFor(model => model.Photo, new { htmlAttributes = new { @class = "form-control" } })*@
                <input type="file" name="UpdatePhoto" />
                @Html.HiddenFor(model=>model.emp.Photo)
                @Html.ValidationMessageFor(model => model.emp.Photo, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.emp.DOB, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.emp.DOB, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.emp.DOB, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.emp.CourseId, "CourseId", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @foreach(var course in @Model.empCourse)
                {
                @Html.RadioButtonFor(m => m.SelectDepartment, course.CourseId) @course.CourseName

                }    
                @*@Html.DropDownList("CourseId", null, htmlAttributes: new { @class = "form-control" })*@
                @Html.ValidationMessageFor(model => model.emp.CourseId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts
    {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">
     $(document).ready(function () {
         $('input:text.date').datepicker();
     });
    </script>
}

控制器编辑

   public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var empsingle = db.Employees.Single(x => x.EmpId == id);

        EmployeeCourseViewModel empcourseViewModel = new EmployeeCourseViewModel
        {
            emp = empsingle,
            empCourse = db.Courses.ToList()
        };
        ViewBag.Gender = new SelectList(db.Genders, "GValue", "GText", empsingle.Gender);

        return View(empcourseViewModel);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "EmpId,FirstName,LastName,Gender,EmailAddress,PersonalWebSite,Photo,DOB,CourseId,SelectDepartment")]
    EmployeeCourseViewModel empCourseVM, HttpPostedFileBase UpdatePhoto)
    {
        if (ModelState.IsValid)
        {
            if (UpdatePhoto == null)
            {
                //;
            }
            else
            {
                string filePath = Server.MapPath("~/Images/" + UpdatePhoto.FileName);
                UpdatePhoto.SaveAs(filePath);
                empCourseVM.emp.Photo = "~/Images/" + UpdatePhoto.FileName;
            }
            empCourseVM.emp.CourseId = empCourseVM.SelectDepartment;
            db.Entry(empCourseVM.emp).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        else
        {
            ViewBag.Gender = new SelectList(db.Genders, "GValue", "GText", empCourseVM.emp.Gender);
            return View(empCourseVM);
        }
    }

}

当我尝试调试时,viewmodel对象为emp和empcourse返回null [empCourseVM.emp.CourseId = empCourseVM.SelectDepartment;]。我尝试过很多建议,但没有帮助我。请帮我解决这个问题。我正在使用MVC5,EF6和VS2015专业版。 对不起,很长的帖子。

员工类

[MetadataType(typeof(EmployeeMap))]
public partial class Employee { }
public  class EmployeeMap
{
    [HiddenInput(DisplayValue = false)]
    //[ScaffoldColumn(false)]
    [Key]   
    public int EmpId { get; set; }

    [DisplayName("First Name")]
    [Required]
    public string FirstName { get; set; }
    [Required]
    [DisplayName("Last Name")]
    public string LastName { get; set; }

    [Required]
    [StringLength(1, MinimumLength =1, ErrorMessage ="Gender should be single character")]
    public string Gender { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [DisplayName("Email Address")]
    public string EmailAddress { get; set; }


    [DataType(DataType.Url)]
    [DisplayName("Personal Web Site")]
    public string PersonalWebSite { get; set; }

    public string Photo { get; set; }


    [Required]
    //[DataType(DataType.Date)]
    [DisplayFormat(DataFormatString ="{0:MM/dd/yyyy}", ApplyFormatInEditMode =true)]
    public DateTime DOB { get; set; }

    //public HttpPostedFileBase user_image_data { get; set; } 
}

课程班

public class CourseMap
{
    [Key]
    [DisplayName("Course Id")]
    public int CourseId{ get; set; }

    [DisplayName("Course Name")]
    [Required]
    public string CourseName { get; set; }
}

HTML代码段 http://i.stack.imgur.com/IRFoI.png

0 个答案:

没有答案