Yazan Rawashdeh Yazan Rawashdeh - 3 months ago 9
C# Question

How to use ViewModels in Edit Action without making another request?

I need a specific answer or solution about this particular case ,
I have

EditVehicleViewModel
that's passed to Edit Vehicle Controller Action like so

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);
}


I need to update the Model based on the changes that's been to the ViewModel , without making a request to get the Vehicle that's changed and
SaveChanges()
on it , while still using this line of code if possible

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


EDIT
Here's my model and ViewModel

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; }
}


Model

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; }
}

Answer

First you have to install any one of the following package from nuget,

PM> Install-Package TinyMapper

OR

PM> Install-Package AutoMapper

then add in your code, if tinymapper is used

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

OR

if automapper is used,

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