如何在编辑操作中使用ViewModel而不进行其他请求?

时间:2015-03-27 14:46:00

标签: c# asp.net-mvc asp.net-mvc-5

我需要针对这个特定案例的具体答案或解决方案, 我已将EditVehicleViewModel传递给编辑车辆控制器操作,如此

public async Task<ActionResult> Edit(EditVehicleViewModel vehiclViewModel)
{
    if (ModelState.IsValid)
    {

         // I NEED TO MAP THE VIEW_MODEL TO THE MODEL HERE 

        db.Entry(vehicleModel).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    return View(vehiclViewModel);
}

我需要根据对ViewModel所做的更改来更新模型,而不是要求更改车辆并更改SaveChanges(),同时仍然使用此功能尽可能的代码行

db.Entry(vehiclViewModel).State = EntityState.Modified;

修改 这是我的模型和ViewModel

视图模型

public class EditVehicleViewModel
{
    [Required]
    public string LicenceNumber { get; set; }

    public int? Year { get; set; }

    public string Color { get; set; }

    [DataType(DataType.Upload)]
    public HttpPostedFileBase ImageUpload { get; set; }

    public string VINNumber { get; set; }
}

模型

public class Vehicle
{
    public int ID { get; set; }

    [Required]
    public string LicenceNumber { get; set; }

    [Required]
    public Nullable<DateTime> Year { get; set; }

    [Required]
    public string Color { get; set; }

    [DataType(DataType.ImageUrl)]
    public string ImageUrl { get; set; }

    [Required]
    public string VINNumber { get; set; }
 }

2 个答案:

答案 0 :(得分:3)

首先,你必须从nuget,

安装以下任何一个软件包

PM&GT;安装包TinyMapper

OR

PM&GT;安装包AutoMapper

然后添加您的代码,如果使用tinymapper

TinyMapper.Bind<Vehicle, EditVehicleViewModel>();
Vehicle vehicleModel = TinyMapper.Map<EditVehicleViewModel>(vehiclViewModel);
db.Entry(vehicleModel).State = EntityState.Modified;

OR

如果使用了automapper,

Mapper.CreateMap<Vehicle , EditVehicleViewModel>();
Vehicle vehicleModel = Mapper.Map<EditVehicleViewModel>(vehiclViewModel);
db.Entry(vehicleModel).State = EntityState.Modified;

答案 1 :(得分:1)

很抱歉,如果这不对。我还不太确定vehicleModel在哪里

public async Task<ActionResult> Edit(EditVehicleViewModel vehiclViewModel)
{
    if (ModelState.IsValid)
    {
         // I am guessing the VINNumber is the identifier
        Vehicle vModel = db.Vehicle.FirstOrDefault(v => v.VINNumber == vehiclViewModel.VINNumber);

        // Mapping here
        vModel.LicenceNumber = vehiclViewModel.LicenceNumber;
        vModel.Year = vehiclViewModel.Year;
        vModel.Color = vehiclViewModel.Color;
        vModel.VINNumber = vehiclViewModel.VINNumber
        vModel.ImageUrl = vehiclViewModel.ImageUrl;

        db.Entry(vModel).State = vModel.ID == 0 ? EntityState.Added : EntityState.Modified;

        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    return View(vehiclViewModel);
}

我认为这是一个帖子,因为它是一个编辑。我可能是错的,但可能是一个想法,在

中添加用于在编辑页面加载时识别它的车辆ID
@Html.Hidden() 

然后可以在寻找需要保存的车辆时将其用作标识符