passing viewmodel to action method, parameter question

I am using a viewmodel for my create view page. In the create method, I have the following

public ActionResult Create([Bind(Include = "AssetID,Name,Description,ManufacturerID,Model,Serial,RegionID,Cost,Notes,Status,DatePurchased,DateAdded")]Asset asset, int[] Licenses) 

it’s weird because this code was working fine but when I added two new fields Model and Name into the view page and bind parameters, the create method started not to work and gave me this error

The model item passed into the dictionary is of type 'InventoryProject.Models.Asset', but this dictionary requires a model item of type 'InventoryProject.ViewModels.AssetCreateViewModel'. 

and I had these two properties in my Asset class all along, I just never included them. I’m assuming that this error is saying the parameter in the create method takes an Asset object and not a AssetCreateViewModel object?

Here is my view model

public class AssetCreateViewModel { public Asset Asset { get; set; } public IEnumerable<License> Licenses { get; set; } public IEnumerable<string> list { get; set; } public SelectList AspNetUsers { get; set; } public SelectList AssetTypes { get; set; } public SelectList Regions { get; set; } public SelectList Statuses { get; set; } public AssetCreateViewModel(HappyEntities db) { //Licenses = new (db.Licenses.ToList(), nameof(License.LicenseID), $"{nameof(Product)}.{nameof(Product.Name)}"); Licenses = (from s in db.Licenses select s).OrderBy(m => m.Product.Name).ToList(); AspNetUsers = new SelectList(db.AspNetUsers.OrderBy(m => m.Name).ToList(), "ID", "Name"); AssetTypes = new SelectList(db.AssetTypes.ToList(), "AssetTypeID", "Category"); Regions = new SelectList(db.Regions.ToList(), "RegionID", "Location"); Statuses = new SelectList(db.Status.ToList(), "StatusID", "Condition"); } } 

My question is, am I supposed to be passing the viewmodel object as opposed to the actual class object? no way around it? I thought the binding could just put all the values it was passed in, and store it into an object of asset, didn’t have to necessarily be the viewmodel object

submitted by /u/ncredibles
[link] [comments]

Leave a Reply