Table values are not showing - ASP.net - c#

This might be a dumb question as I'm new to the MVC pattern in asp.net.
I'm trying to access to the value in my database but the values don't get rendered
on the view page.
here's the code I have written.
code for the "Resturant" model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace OdetoFood.Models
{
[Table("Resturants")]
public class Resturant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<ResturantReviews> Reviews { get; set; }
}
}
here's my DbContext model:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace OdetoFood.Models
{
public class OdeToFoodDb : DbContext
{
public DbSet<Resturant> Resturants { get; set; }
public DbSet<ResturantReviews> Reviews { get; set; }
}
}
Code for the controller class:
public class HomeController : Controller
{
OdeToFoodDb _db = new OdeToFoodDb();
public ActionResult Index()
{
var model = _db.Resturants.ToList();
return View(model);
}
and here's the view that should be displaying the values:
#model IEnumerable<OdetoFood.Models.Resturant>
#{
ViewBag.Title = "Home Page";
}
#foreach (var item in Model)
{
<h3>#item.Name</h3>
<div>#item.City, #item.Country</div>
<div>#item.Id</div>
}
the connection string in Web.config is setup like this:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-OdetoFood-20150611025411.mdf;Initial Catalog=aspnet-OdetoFood-20150611025411;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
What am I doing wrong here?

This would be the seed method for that project:
protected override void Seed(OdeToFood.Models.OdeToFoodDb context)
{
context.Restaurants.AddOrUpdate(r => r.Name,
new Restaurant { Name = "Sabatino's", City = "Baltimore", Country = "USA" },
new Restaurant { Name = "Great Lake", City = "Chicago", Country = "USA" },
new Restaurant
{
Name = "Smaka",
City = "Gothenburg",
Country = "Sweden",
Reviews =
new List<RestaurantReview>{
new RestaurantReview{ Rating = 9, Body="Great Food!" }
}
});
}

Related

Cant retrieve information from table in ASP.NET Entity Framework

Can't find why the object I'm supposed to retrieve from database is always empty, despite the fact that the table has 3 elements. In the view, Model.Count is always == 0. New to dotnet, stuck for hours.
What I did :
connection string in app.config
connection string in web.config
<connectionStrings>
<add name="masterEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-K74JGDL\SQLEXPRESS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="DBModel" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1 .msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-K74JGDL\SQLEXPRESS;initial catalog=core2DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
restart SQL Server
Controller seems to know about my tables since it autocomplete tables and keys.
Posts.cs
namespace WebApplication1.Data
{
public partial class Posts
{
public int Id { get; set; }
public Nullable<int> Post_owner { get; set; }
public string Post_content { get; set; }
public Nullable<int> Post_like_count { get; set; }
public virtual Users Users { get; set; }
}
}
Model1.Context.Cs:
namespace WebApplication1.Data
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class DBModel : DbContext
{
public DBModel() : base("DBModel")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
/* Database.SetInitializer<DBModel>(null);
base.OnModelCreating(modelBuilder);*/
}
public virtual DbSet<Posts> Posts { get; set; }
public virtual DbSet<Users> Users { get; set; }
}
}
In PostController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Data;
using WebApplication1.Models;
using System.Diagnostics;
namespace WebApplication1.Controllers
{
public class PostController : Controller
{
// GET: Post
public ActionResult Index()
{
var context = new DBModel();
List<Posts> postsList = new List<Posts>();
if (!context.Posts.Any())
{
/* postsList = 3;*/
}
postsList = context.Posts.ToList();
/* using (var context = new DBModel())
{
postsList = context.Posts.ToList();
}*/
return View(postsList);
}
}
}
and the view is (Index.cshtml) :
#model List<WebApplication1.Data.Posts>
#{
ViewBag.Title = "Index";
}
<h2>Hello Peyo</h2>
<div>#Model</div>
#foreach (var post in Model)
{
<div><span>Nom: </span><span>#post.Post_content</span></div>
}
<span>Hello again</span>

How to make a dropdownlist with data from database in ASP.NET Core MVC

I have figured out how to make a dropdownlist with static data, but I want to display data from my database. How do I fill my list with data from the model Neighbourhoods? I want to display all the NeighbourhoodNames in my dropdown.
I am using .net core 5.0 with MVC
My cshtml code:
<select asp-for="Neighbourhood" asp-items="Model.NeighbourhoodList"></select>
My Model:
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace MyProject.Models
{
[Keyless]
public partial class Neighbourhoods
{
public string NeighbourhoodGroup { get; set; }
public string NeighbourhoodName { get; set; }
public List<SelectListItem> NeighbourhoodList { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "a", Text = "New York" },
new SelectListItem { Value = "b", Text = "Los Angeles" },
};
}
}
My Controller:
// GET: Neighbourhoods/Create
public IActionResult Create()
{
var vm = new Neighbourhoods();
return View(vm);
}

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint on my asp.net app

I have problem with my first web application , when I start the application Im getting this error:
1st img
2nd img
The application is about car rental.
1.I will show my data structure: for CarCategory and SmallCars
--CARCATEGORY
namespace CarRentalSystem.Data.Models
{
using System.Collections.Generic;
using CarRentalSystem.Data.Common.Models;
public class CarCategory : BaseDeletableModel<int>
{
public CarCategory()
{
this.SmallCars = new HashSet<SmallCarInfo>();
}
public string Name { get; set; }
public string Title { get; set; }
public string CarDescription { get; set; }
public string CarImageUrl { get; set; }
public virtual ICollection<SmallCarInfo> SmallCars { get; set; }
}
}
--SMALLCARS
namespace CarRentalSystem.Data.Models
{
using System;
using System.Collections.Generic;
using System.Text;
using CarRentalSystem.Data.Common.Models;
public class SmallCarInfo : BaseModel<int>
{
public string CarModel { get; set; }
public string CarImage { get; set; }
public int CarPricePerDay { get; set; }
public int CategoryId { get; set; }
public virtual CarCategory Category { get; set; }
}
}
Now I make a migration and im going to make two SEEDERS with data:
--CAR CATEGORIES SEEDER
namespace CarRentalSystem.Data.Seeding
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CarRentalSystem.Data.Models;
using Microsoft.EntityFrameworkCore.Internal;
public class CategoriesSeeder : ISeeder
{
public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
{
if (dbContext.CarCategories.Any())
{
return;
}
var carCategories = new List<(string Name, string ImageUrl, string CarDescription)>
{
("Small car", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/city-car-128.png",
"This is a compact car with 2/3 doors. Perfect for couples with small luggage."),
("Medium car", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/sedan-128.png",
"This is medium car with 4/5 doors. Perfect for small families with average luggage."),
("Minivan", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/minivan-128.png",
"This is a large car with 4/5 doors + extra seats. Perfect for large families with average luggage."),
("Minibus", "https://cdn4.iconfinder.com/data/icons/car-silhouettes/1000/van-128.png",
"This is a large car with 8+1 seats with big trunk. Perfect for large families or companies with a lot of luggage"),
};
foreach (var category in carCategories)
{
await dbContext.CarCategories.AddAsync(new CarCategory
{
Name = category.Name,
Title = category.Name,
CarImageUrl = category.ImageUrl,
CarDescription = category.CarDescription,
});
}
dbContext.SaveChanges();
}
}
}
--SMALL CARS SEEDER
namespace CarRentalSystem.Data.Seeding
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using CarRentalSystem.Data.Models;
using Microsoft.EntityFrameworkCore.Internal;
public class SmallCarsSeeder : ISeeder
{
public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
{
if (dbContext.SmallCar.Any())
{
return;
}
var carDetails = new List<(string CarModel, string CarImage, int CarPricePerDay)>
{
("Nissan Micra", "https://5.imimg.com/data5/BV/XC/RV/SELLER-85643879/nissan-micra-xl-o-cvt-turquoise-blue-1198-cm3-car-500x500.jpg", 15),
("Ford Fiesta", "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT_s9VktREdvkJUF9uU2V4NWIOzxU4Olk8IdTO2DOfjbAnsJQcU&usqp=CAU", 15),
};
foreach (var details in carDetails)
{
await dbContext.SmallCar.AddAsync(new SmallCarInfo
{
CarModel = details.CarModel,
CarImage = details.CarImage,
CarPricePerDay = details.CarPricePerDay,
});
}
dbContext.SaveChanges();
}
}
}
3.Now Im making CONTROLLERS + SERVICES/VIEW-MODELS and VIEWS
--CONTROLLER FOR CHOOSING SMALL CARS
namespace CarRentalSystem.Web.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Data;
using CarRentalSystem.Web.ViewModels.Categories;
using Microsoft.AspNetCore.Mvc;
public class CategoriesController : Controller
{
private readonly ICategoriesService categoriesService;
public CategoriesController(ICategoriesService categoriesService)
{
this.categoriesService = categoriesService;
}
public IActionResult ChooseCars(string name)
{
var viewModel =
this.categoriesService.GetByName<CarsListViewModel>(name);
return this.View(viewModel);
}
}
}
--"GetByName" SERVICE LOGIC
namespace CarRentalSystem.Services.Data
{
using System;
using System.Collections.Generic;
using System.Text;
public interface ICategoriesService
{
IEnumerable<T> GetAll<T>(int? count = null);
T GetByName<T>(string name);
}
}
namespace CarRentalSystem.Services.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CarRentalSystem.Data.Common.Repositories;
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Mapping;
public class CategoriesService : ICategoriesService
{
private readonly IDeletableEntityRepository<CarCategory> categoriesRepository;
public CategoriesService(IDeletableEntityRepository<CarCategory> categoriesRepository)
{
this.categoriesRepository = categoriesRepository;
}
public IEnumerable<T> GetAll<T>(int? count = null)
{
IQueryable<CarCategory> query =
this.categoriesRepository.All();
if (count.HasValue)
{
query = query.Take(count.Value);
}
return query.To<T>().ToList();
}
public T GetByName<T>(string name)
{
var category = this.categoriesRepository.All()
.Where(x => x.Name.Replace(" ", "-") == name.Replace(" ", "-"))
.To<T>().FirstOrDefault();
return category;
}
}
}
-- TWO VIEW-MODELS THAT GET DATA FROM DATA MODELS AND MAPPING
namespace CarRentalSystem.Web.ViewModels.Categories
{
using System;
using System.Collections.Generic;
using System.Text;
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Mapping;
public class CarsListViewModel : IMapFrom<CarCategory>
{
public string Name { get; set; }
public string Title { get; set; }
public string CarDescription { get; set; }
public IEnumerable<CarsViewModel> SmallCars { get; set; }
}
}
namespace CarRentalSystem.Web.ViewModels.Categories
{
using System;
using System.Collections.Generic;
using System.Text;
using CarRentalSystem.Data.Models;
using CarRentalSystem.Services.Mapping;
public class CarsViewModel : IMapFrom<SmallCarInfo>
{
public string CarModel { get; set; }
public string CarImage { get; set; }
public int CarPricePerDay { get; set; }
}
}
--THE VIEW WITH RAZOR
#using CarRentalSystem.Common
#model CarRentalSystem.Web.ViewModels.Categories.CarsListViewModel
#{
this.ViewData["Title"] = "Cars";
}
<h1 class="display-3">#Model.Title</h1>
<div class="row">
#foreach (var details in Model.SmallCars)
{
<div class="card" style="width: 18rem;">
<img src="#details.CarImage" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">#details.CarModel</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">#details.CarPricePerDay euro.</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
<div class="card-body">
Card link
Another link
</div>
</div>
}
</div>
And now when I start the app Im getting the error that I showed at the top.
Picture of the CARCATEGORY table
Picture of the SMALLCARS table
How can I fix the problem with FK confliction? Thanks!

MVC get dropdownlist selected value to TempData

I am using an MVC model and i want to save the selected value from a dropdownlist.
here is what i have so Far
Model.
namespace FormsAuthenticationMVC.Models
{
using System;
using System.Collections.Generic;
public partial class Report_Security
{
public int ID { get; set; }
public Nullable<int> UserName_ID { get; set; }
public string ReportName { get; set; }
public string Report_Url { get; set; }
public string EmbedCode { get; set; }
public List<Report_Security> ReportList { get; set; }
}
}
My Controller
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FormsAuthenticationMVC.Models;
namespace FormsAuthenticationMVC.Controllers
{
//[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Reports()
{
// this is working fine. the dropdown is populated from the model correctly.
ViewBag.Message = "O2 Dashboard";
ASP_AuthEntities ReportTable = new ASP_AuthEntities();
var getReportTable = ReportTable.Report_Security.ToList();
SelectList list = new SelectList(getReportTable, "EmbedCode", "ReportName");
ViewBag.ReportListName = list;
return View();
}
[HttpPost]
public ActionResult Reports(Report_Security model, string Code)
{
if (ModelState.IsValid)
TempData["HtmlSelected"] = Code; // = This is where i shall set the dropdown value
return View(model);
}
}
}
and my view
#model FormsAuthenticationMVC.Models.Report_Security
#{
<h2>#ViewBag.Message</h2>
}
#Html.DropDownListFor(r =>r.EmbedCode, new SelectList(Model.EmbedCode,"EmbedCode"),"Select Report")
<h5>#TempData["HtmlSelected"]</h5> #*----- SELECTED DROPDOWN VALUE*#
When i run debug and i put a breakpoint in my view at the #Html.DropDownListFor ...... line i get the following error.
System.Web.Mvc.WebViewPage.Model.get returned null.
Could someone help me out please.

How can i create a Partial View for MVC4 or MVC 5 using Entity Framework (.edmx Model) with Razor Views?

I'm having a lot of trouble trying to create a partial view on my home controller from a .edmx model.
I cannot change the properties of this model because it is a part of another system that I am building this Website around.
I have spent a very long time trying to work this out and have came here to hopefully get some help and advice.
Aim: Render a partial _Patient.cshtml view on the Homepage using models in an .edmx model. I would like for you to show me where I have gone wrong as it does not work.
What is the problem?
I get multiple errors such as:
model: : EntityType model has no key defined. Define the key for this entity type.
The model item passed into the dictionary is of type 'Models', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`
using the generic type 'system.collections.generic.ienumerable requires 1 type arguments MVC
Currently I'm getting this error but I get the feeling that it's at the front of a long list of them.
The model item passed into the dictionary is of type 'FaceToFaceWebsite.Models.PatientListViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[FaceToFaceWebsite.Models.PatientListViewModel]'.
Below is the .edmx
(as I cannot post images yet..
User (edmx)
-Properties-
UserID
CodeName
UseBriefInstructions
Device_DeviceID
-Navigation Properties-
Device
RegimeItems
Device
-Properties-
DeviceID
Name
-Navigation Properties-
Users
Session
-Properties-
SessionID
ActiveUserID
ActiveDeviceID
StartedAt
ReachedFinish
-Navigation Properties-
SessionExcercises
(the Edmx is alot bigger than shown however these are the models that i currently need to use. however session and user are infact linked through another model)
HomeController.cs
using FaceToFaceWebsite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Web;
using System.Web.Mvc;
using PagedList;
using System.Web.UI;
using System.Configuration;
using System.Collections;
namespace FaceToFaceWebsite.Controllers
{
public class HomeController : Controller
{
public F2FDataEntities _db = F2FDataEntities();
[OutputCache(CacheProfile = "Long", VaryByHeader = "X-Requested-With", Location = OutputCacheLocation.Server)]
public ActionResult Index(string searchTerm = null, int page = 1)
//public ActionResult Index()
{
var model =
_db.UserID.ToList()
.OrderByDescending(u =>u.UserID)
.Take(10)
.Select (u => new PatientListViewModel
{
CodeName = u.CodeName,
Name = u.Name
}).ToPagedList(page, 10);
return PartialView("_Patient", new FaceToFaceWebsite.Models.PatientListViewModel());
////return View(model);
////ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Patients()
{
ViewBag.Message = "";
return View();
}
public ActionResult Help()
{
ViewBag.Message = "";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Contact Us";
return View();
}
protected override void Dispose(bool disposing)
{
if (_db != null)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
PatientListViewModel
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data.Entity;
namespace FaceToFaceWebsite.Models
{
public class PatientListViewModel
{
public virtual ICollection<User> CodeName { get; set; }
public virtual ICollection<Session> ReachedFinish { get; set; }
public virtual ICollection<Device> Name { get; set; }
}
}
Views/Home/Index.cshtml
System.Collections.Generic.IEnumerable<FaceToFaceWebsite.Models.PatientHomeViewModel>*#
#{
ViewBag.Title = "Home Page";
}
#Html.Partial("_Patient", Model)
Views/Home/_Patient.cshtml
#model IEnumerable<PatientListViewModel>
#foreach (var item in Model)
{
<div>
<h4>UserID: #item.CodeName</h4>
<span>Finished: #item.ReachedFinish</span>
<p>Machine: #item.Name</p>
<hr />
</div>
}
PatientProfile.cs (i tried making another model to as a different approach but to no success)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace FaceToFaceWebsite.Models
{
public class PatientProfile : DbContext
{
public PatientProfile() : base("F2FDataEntities")
{
}
public DbSet<User> UserID { get; set; }
public DbSet<Device> Name { get; set; }
//public DbSet<RestaurantReview> Reviews { get; set; }
public System.Data.Entity.DbSet<FaceToFaceWebsite.Models.PatientListViewModel> PatientListViewModels { get; set; }
}
}
F2FDataDB.cs(I Tried creating another Db that would use the models from the edmx)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace FaceToFaceWebsite.Models
{
public class F2FDataEntities : DbContext
{
public F2FDataEntities() : base("name=F2FDataEntities")
{
}
public DbSet<User> UserID { get; set; }
public DbSet<User>CodeName { get; set; }
//public DbSet<Session> SessionDB { get; set; }
public DbSet<Device> Name { get; set; }
public System.Data.Entity.DbSet<FaceToFaceWebsite.Models.PatientListViewModel> PatientListViewModel { get; set; }
}
}
I've posted everything i see as relevant, if you need anymore information please let me know.
I apologise if the solution is simple, im new to MVC and this problem has gone on for quite some time.
---------UPDATE 2.0-------------
Views/home/index.cshtml
#model FaceToFaceWebsite.Models.PatientListViewModel
#{
ViewBag.Title = "Home Page";
}
#Html.Partial("_Patient", Model.PatientProfile)
views/shared/_Patient.cshtml (partial view)
#model List<PatientProfile>
#foreach (var item in Model)
{
<div>
<h4>UserID: #item.CodeName</h4>
<div>
#*<span>UserName: #item.CodeName</span>*#
</div>
#*<span>Started Session at: #item.StartedAt</span>*#
<span>Finished: #item.ReachedFinish</span>
<p>Machine: #item.Name</p>
<hr />
</div>
}
patientlistviewmodel.cs
namespace FaceToFaceWebsite.Models
{
public class PatientListViewModel
{
public List<Patient> PatientProfile { get; set; }
}
public class Patient
{
public int UserID { get; set; }
public string CodeName { get; set; }
}
}
HomeController.cs
namespace FaceToFaceWebsite.Controllers
{
public class HomeController : Controller
{
public F2FDataEntities _db = new F2FDataEntities();
public ActionResult Index()
{
var viewModel = new PatientListViewModel();
viewModel.PatientProfile = new List<Patient>();
return View(viewModel);
}
}
}
Models/PatientProfile.cs
namespace FaceToFaceWebsite.Models
{
public class PatientProfile : DbContext
{
public PatientProfile() : base("F2FDataEntities")
{
}
public DbSet<User> UserID { get; set; }
public DbSet<User> CodeName{ get; set; }
public DbSet<Device> Name { get; set; }
public DbSet<Session> ReachedFinish { get; set; }
}
}
I am currently getting this error:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[FaceToFaceWebsite.Models.Patient]', but this dictionary requires a model item of type
I am getting this error at "..#Html.Partial("_patient", Model.PatientProfile)"
_Patient (Partial view)
#model List<PatientProfile>
#foreach (var item in Model)
{
<div>
<h4>UserID: #item.CodeName</h4>
<span>Finished: #item.ReachedFinish</span>
<p>Machine: #item.Name</p>
<hr />
</div>
}
1.
You are passing back the PartialView as a Result:
return PartialView("_Patient", new FaceToFaceWebsite.Models.PatientListViewModel());
Change this to return View(model); In your Index function. This will return your Home Page "Views/Home/Index.cshtml", and in this Index view you have:
#Html.Partial("_Patient", Model)
Which will Render the Partial View. But you are passing the wrong Model to your Index View: in Controller you are passing PatientListViewModelBut in you index you have: IEnumerable<FaceToFaceWebsite.Models.PatientHomeViewModel>.
So either you pass IEnumerable<FaceToFaceWebsite.Models.PatientHomeViewModel>,
like this:
public ActionResult Index(){
return PartialView(new FaceToFaceWebsite.Models.PatientListViewModel());
}
And then you can call Partial View like this:
#model IEnumerable<FaceToFaceWebsite.Models.PatientHomeViewModel>
#{
ViewBag.Title = "Home Page";
}
#Html.Partial("_Patient", Model)
What you should do.
Controller:
public ActionResult Index()
{
var viewModel = PatientListViewModel();
viewModel.PatientList = new List<Patients>();
viewModel.CustomerList = new List<Cusotmer>();
return View(viewModel);
}
Index.cshtml
#model PatientListViewModel
#* Considering your partial view is in Shared Foler*#
// Note Passing the Correct Model to Partial View
#Html.Partial("_Patient", Model.PatientsList)
// Another Example:
#Html.Partial("_Customer", Model.CustomerList)
Your _Patient.cshtml (partial View)
#model List<PatientsList>
#foreach(var item in Model){
item.Name
}
Your _Customer.cshtml (partial View) // Another Example
#model List<Custom>
#foreach(var item in Model){
item.Name
}
Your ViewModel:
public class PatientListViewModel{
public List<Patient> PatientsList {get;set;}
public List<Customer> CustomerList{get;set;}
}
public class Patient{
public string Name {get;set;
}
// Another Example
public Class Customer{
public string Name{get;set;
}
UPDATE
#model FaceToFaceWebsite.Models.PatientListViewModel
#{
ViewBag.Title = "Home Page";
}
// PatientListViewModel this is the Name of you class
// To Access your Model you always have to use Model. Not the Class Name
// PatientListViewModel is the Class name
// Model is the Object --> You passed from Controller.
// Use Model.PatientProfile
// Not PatientListViewModel.PatientProfile
#Html.Partial("_Patient", Model.PatientProfile)

Categories