Asp.net mvc 5 使用Automapper将viewmodel映射到域模型会在后期操作中返回空值吗?

Asp.net mvc 5 使用Automapper将viewmodel映射到域模型会在后期操作中返回空值吗?,asp.net-mvc-5,ef-code-first,automapper,Asp.net Mvc 5,Ef Code First,Automapper,我有一个实体模型,记录一些员工信息。我有一个类似的视图模型 在我的创建操作中,我创建了viewmodel的一个新实例,并传递了一些下拉列表 在createpost操作中,我使用AutoMapper将返回的视图模型映射到实体模型 我做错了,因为回发的数据似乎不包含任何视图模型数据。它只包含空值 你知道我做错了什么吗 控制器 //获取:/TimeCreditEntries/Create 公共操作结果创建() { var Model=new TimeCreditEntryViewModel();//创

我有一个实体模型,记录一些员工信息。我有一个类似的视图模型

在我的创建操作中,我创建了viewmodel的一个新实例,并传递了一些下拉列表

在createpost操作中,我使用AutoMapper将返回的视图模型映射到实体模型

我做错了,因为回发的数据似乎不包含任何视图模型数据。它只包含空值

你知道我做错了什么吗

控制器

//获取:/TimeCreditEntries/Create
公共操作结果创建()
{
var Model=new TimeCreditEntryViewModel();//创建一个新的viewmodel来保存TimeCreditEntry
Model.StationList=新建选择列表(getStations(),“StationId”,“Code”);
Model.authorizedEmployee=新选择列表(getEmployees(),“EmployeeId”,“FullNameSurnameFirst”);
Model.authorizedPayment=新选择列表(getPaymentTypes(),“PaymentTypeId”,“代码”);
返回视图(模型);//以模型作为参数返回视图。
}
//POST:/TimeCreditEntries/Create
//若要防止套印攻击,请启用要绑定到的特定属性,例如
//更多详细信息请参见http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果创建([Bind(包括=“TimeCreditEntryId,RecordedDate,TimeCreditDate,ShiftId,StationId,AuthorizationEmployeeId,AuthorizedEmployeeId,ModifiedDate”)]TimeCreditEntryViewModel timeCreditEntry)
{
if(ModelState.IsValid)
{
CreateMap();
添加(Mapper.Map(timeCreditEntry));
db.SaveChanges();
返回重定向到操作(“寄存器”);}
ViewBag.authorizedEmployeeId=新的选择列表(db.EmployeeId,“EmployeeId”,“Title”,timeCreditEntry.authorizedEmployeeId);
ViewBag.authorizationEmployeeId=新的选择列表(db.EmployeeId,“EmployeeId”,“Title”,timeCreditEntry.authorizationEmployeeId);
ViewBag.ShiftId=新选择列表(db.Shifts,“ShiftId”,“Code”,timeCreditEntry.ShiftId);
返回视图(timeCreditEntry);
}
看法

@model ATAS.Models.ViewModels.TimeCreditEntryViewModel
@{
ViewBag.Title=“创建”;
}
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
申请使用时间信用证
谁
@Html.DropDownListFor(model=>model.authorizedEmployee,model.authorizedEmployee,“选择员工”,新建{@class=“form control”})
@Html.ValidationMessageFor(model=>model.authorizedEmployeeId)
@LabelFor(model=>model.TimeCreditDate,新的{@class=“controllabel col-md-2”})
@Html.TextBoxFor(model=>model.TimeCreditDate,新的{@class=“datepicker”,id=“vacation”})
@Html.ValidationMessageFor(model=>model.TimeCreditDate)
R
哪里
@DropDownListFor(model=>model.StationList,model.StationList,“选择站点”,新建{@class=“form control”})
哪一个
@DropDownList(“Shift”,new SelectList(string.Empty,“Value”,“Text”),new{@class=“form control”})
取消
提交
}
$(文档).ready(函数(){
$('.datepicker').datepicker()
$(“Shift”).prop(“disabled”,true);
//下拉列表Selectedchange事件
$(“#StationList”).change(函数(){
$(“#Shift”).empty();
if($(“#StationList”).val()!=“”){
$.ajax({
键入:“POST”,
url:'@url.Action(“GetShiftsByStation”),//我们正在调用json方法
数据类型:“json”,
数据:{selectedValue:$(“#StationList”).val()},
//这里我们获取所选站点的值,并将相同的值作为输入传递给json方法getShift。
成功:功能(移位列表){
//states包含JSON格式的列表
//从控制器传递的状态数
$(“#Shift”).append(“+”选择Shift“+”);
$。每个(移位列表,函数(i,移位){
$(“#Shift”).append(“”+Shift.Text+“”);
//这里我们添加了轮班的选项
$(“#Shift”).prop(“禁用”,false);
});
},
错误:函数(ex){
警报(“检索班次失败”。+ex);
}
});
返回false;
}
否则{
$(“#Shift”).empty();
$(“Shift”).prop(“disabled”,true);
}
})
});

您的代码存在许多潜在问题。首先,删除
[Bind]
属性-您使用的是视图模型,这意味着视图模型应该只包含您需要显示/编辑的属性。接下来,dropdownlists需要绑定到值类型属性,而不是
SelectList
本身-
@Html.DropDownListFor(m=>m.authorizedEmployeeId,Model.authorizedEmployee)
-我建议将名称更改为
授权员工列表
或类似名称,以避免混淆。谢谢-MVC对我来说是新事物。开始进行这些更改,但您确实需要显示您的模型,以便查看您还有哪些其他问题。例如,您的
[Bind]
属性表明您有一个名为
RecordedDate
的属性,但在视图中没有用于该属性的表单控件,因此不会绑定任何内容。
   // GET: /TimeCreditEntries/Create
    public ActionResult Create()
    {
        var Model = new TimeCreditEntryViewModel();  //Create a new viewmodel to hold the TimeCreditEntry
        Model.StationList = new SelectList(getStations(), "StationId", "Code");
        Model.AuthorisedEmployee = new SelectList(getEmployees(), "EmployeeId", "FullNameSurnameFirst");
        Model.AuthorisedPayment = new SelectList(getPaymentTypes(), "PaymentTypeId", "Code");
        return View(Model); //View is returned with model as parameter.
   }



    // POST: /TimeCreditEntries/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "TimeCreditEntryId,RecordedDate,TimeCreditDate,ShiftId,StationId,AuthorisingEmployeeId,AuthorisedEmployeeId,ModifiedDate")] TimeCreditEntryViewModel timeCreditEntry)
    {
        if (ModelState.IsValid)
        {
            Mapper.CreateMap<TimeCreditEntryViewModel, TimeCreditEntry>();
            db.TimeCreditEntries.Add(Mapper.Map<TimeCreditEntryViewModel, TimeCreditEntry> (timeCreditEntry));
            db.SaveChanges();
            return RedirectToAction("Register"); }
                                             ViewBag.AuthorisedEmployeeId = new SelectList(db.Employees, "EmployeeId", "Title", timeCreditEntry.AuthorisedEmployeeId);
              ViewBag.AuthorisingEmployeeId = new SelectList(db.Employees, "EmployeeId", "Title", timeCreditEntry.AuthorisingEmployeeId);
              ViewBag.ShiftId = new SelectList(db.Shifts, "ShiftId", "Code", timeCreditEntry.ShiftId);
        return View(timeCreditEntry);
    }
@model ATAS.Models.ViewModels.TimeCreditEntryViewModel

@{
ViewBag.Title = "Create";
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
    <fieldset>
        <legend>Request to use time credit</legend>
        <div class="form-group">
            <label class="col-md-2 control-label" for="AuthorisedEmployee">Who</label>
            <div class="col-md-2">
                @Html.DropDownListFor(model => model.AuthorisedEmployee, Model.AuthorisedEmployee, "Select Employee", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.AuthorisedEmployeeId)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.TimeCreditDate, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.TimeCreditDate, new { @class = "datepicker", id = "vacation" })
                @Html.ValidationMessageFor(model => model.TimeCreditDate)
            </div>r
        </div>
        <div class="form-group">
            <label class="col-md-2 control-label" for="StationList">Where</label>
            <div class="col-md-2">
                @Html.DropDownListFor(model => model.StationList, Model.StationList, "Choose Station", new { @class = "form-control" })
            </div>
        </div>
        <div class="form-group">

            <label class="col-md-2 control-label" for="Shift">Which</label>
            <div class="col-md-2">
                @Html.DropDownList("Shift", new SelectList(string.Empty, "Value", "Text"), new { @class = "form-control" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-lg-10 col-lg-offset-2">
                <button class="btn btn-default" type="reset">Cancel</button>
                <button class="btn btn-primary" type="submit">Submit</button>
            </div>
        </div>
    </fieldset>
</div>
}

<script src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $('.datepicker').datepicker()


    $("#Shift").prop("disabled", true);
    //Dropdownlist Selectedchange event
    $("#StationList").change(function () {
        $("#Shift").empty();
        if ($("#StationList").val() != "") {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetShiftsByStation")', // we are calling json method
                dataType: 'json',
                data: { selectedValue: $("#StationList").val() },
                // here we are get value of selected Station and passing same value as input to json method GetShifts.
                success: function (shiftList) {
                    // states contains the JSON formatted list
                    // of states passed from the controller
                    $("#Shift").append('<option value="' + null + '">' + "Choose shift" + '</option>');

                    $.each(shiftList, function (i, shift) {
                        $("#Shift").append('<option value="' + shift.Value + '">' + shift.Text + '</option>');
                        // here we are adding option for shifts
                        $("#Shift").prop("disabled", false);
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve shifts.' + ex);
                }
            });
            return false;
        }
        else {
            $("#Shift").empty();
            $("#Shift").prop("disabled", true);
        }
    })
});