Mark Tabor

Mark Tabor

  • 586
  • 2k
  • 464.4k

ViewModel In MVC 4

Sep 14 2016 5:45 AM
I have a simple website build in MVC4 I do not know how to use multiple models in a single view so Now I have two models used on one view so i made a ViewModel 
public class viewModelVm
{
public List<slider> slider { get; set; }
public List<Service> Service { get; set; }
}
my service class and slider class is also shown below
public class Service
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public List<Service> Getdata()
{
String connectionString = "Data Source=ASPKCO-DANISH\\SQLEXPRESS1;Initial Catalog=PakeezaSodagran;Integrated Security=True;";
String sql = "SELECT * FROM Service";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
var model = new List<Service>();
while (rdr.Read())
{
var service = new Service();
service.ID = Convert.ToInt32(rdr["ID"]);
service.Name = rdr["Name"].ToString();
service.Description = rdr["Description"].ToString();
service.Image = rdr["Image"].ToString();
model.Add(service);
}
return model;
}
}
}
my slider class is as below
public class slider
{
public string src { get; set; }
public string title { get; set; }
}
Now I have a main page in which i have a link for service page and my service controller code is given below
public ActionResult Index()
{
Service sr=new Service();
viewModelVm vm = new viewModelVm();
vm.Service = sr.Getdata();
return View(vm);
}
 
My Service Index View is below 
@model List<BusinessApplicationTemplate.ViewModel.viewModelVm>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Image</th>
</tr>
@foreach (var Service in Model.Service)
{
<tr>
<td>@Service.ID</td>
<td>@Service.Name</td>
<td>@Service.Description</td>
<td>@Service.Image</td>
</tr>
}
</table>
when i click the service link i am getting that error
"'System.Collections.Generic.List<BusinessApplicationTemplate.ViewModel.viewModelVm>' does not contain a definition for 'Service' and no extension method 'Service' accepting a first argument of type 'System.Collections.Generic.List<BusinessApplicationTemplate.ViewModel.viewModelVm>' could be found (are you missing a using directive or an assembly reference?)" 
Source Error:

 
Line 14:     </tr> Line 15:      Line 16:     @foreach (var Service in Model.Service) Line 17:     { Line 18:     <tr>
 
 

Answers (7)