I realized last week that my view model is populating with a list of records when all I really want is a single record of the selected record from my view. I've deduced that it is my view model that is wrong but I can't seem to wire my brain on how to change it so it just spits out the selected record and not a list of records from the database.
public class SummaryVM : BaseViewModel
{
public IList<RecordVM> Records { get; set; }
public SummaryVM()
{
this.Records = new List<RecordVM>();
}
}
I am guessing I am over thinking it like I do everything.
EDIT:
New ViewModel
public class SummaryVM : BaseViewModel
{
public RecordVM Record { get; set; }
}
My Controller
public ActionResult Summary(int id)
{
var vm = new SummaryVM
{
Record = new RecordVM()
};
return View(vm);
}
Change the collection to a single instance ?
public class SummaryVM : BaseViewModel
{
public RecordVM Record { get; set; }
}
Now you have to make sure that wherever you are using this view model,your code is updated to treat it as a single object instead of collection (No foreach loop etc on the Record
property)
Note that, we do not have a constructor which initializes the Record property to a Record instance. So you need to explicitly do that before accessing any property on the record type
var vm= new SummaryVM { Record = new RecordVM() };
vm.RecordId = 123;
Do a null
on the Record property before accessing any of it's properties to prevent the "Object Reference not set to an instance" error
@model SummaryVM
<h2>Record</h2>
@if(Model.Record!=null)
{
<h3>@Model.Record.RecordI</h3>
}