Hi Is it possible to access the different model properties for same view
My VisitorsViewModel model
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
My View_VisitorsForm Model
public System.Guid VisitingID { get; set; }
public string Employee { get; set; }
public string CustomerName { get; set; }
public Nullable<System.DateTime> VisitingDate { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
public string SpendTime { get; set; }
public string POVisit { get; set; }
I want to create 5 fields in view FromDate,Todate,CustomerName,Povisit ,StartTime,EndTime Employee. But all these fields properties in different models. Is it possible to access two different model properties in same view? i tried to explain my issue as per my level best. please any one give me solution.
Advance thanks..
As mentioned by mwilczynski, a view has one viewmodel only. The idea being the model contains exactly the data the view needs to render the page. Ideally, nothing more and nothing less.
From your image, it looks as if you need a viewmodel with a collection of data items to render the grid (visiting date ... Next appointment). This is possible:
public class VisitorsViewModel
{
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public ICollection<VisitViewModel> Visits { get; set; }
}
Where VisitViewModel
is the viewmodel that contains the data retrieved from the database to show in the grid:
public class VisitViewModel
{
public string CustomerName { get; set; }
public string PoVisit { get; set; }
public string StartTime { get; set; }
public string EndTime { get; set; }
public string Employee { get; set; }
}
The controller would look something like:
public ActionResult displaycustomer()
{
// Get data from database
List<View_VisitorsForm> objvisitlist = (from v in db.View_VisitorsForm select v).ToList();
// Create a new viewmodel and fill it with the data you want displayed
VisitorsViewModel viewmodel = new VisitorsViewModel
{
FromDate = DateTime.Now.AddDays(-7), //(some default value)
ToDate = DateTime.Now, //(some default value)
Visits = new List<VisitViewModel>()
};
foreach (View_VisitorsForm visit in objvisitlist)
{
viewmodel.Visits.Add(new VisitViewModel
{
CustomerName = visit.CustomerName,
PoVisit = visit.POVisit,
StartTime = visit.StartTime,
EndTime = visit.EndTime,
Employee = visit.Employee
}
}
// return a ViewResult with the viewmodel
return View(viewmodel);
}
In the view, you can access the properties in the ICollection<VisitViewModel>
like so (I assume you want the visit date in a table):
<table>
@foreach (var visit in Model.Visits)
{
<tr>
<td>
@Html.DisplayValueFor(m => visit.CustomerName)
</td>
<td>
@Html.DisplayValueFor(m => visit.PoVisit)
</td>
</tr>
}
</table>