asp.net mvc ViewModel result wont appear - asp.net

i have this table
[Table("Quiz")]
public class Quiz
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int QuizId { get; set; }
public string Content { get; set; }
public string Submitby { get; set; }
public virtual ICollection<Score> Scores { get; set; }
}
and this
[Table("Score")]
public class Score
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ScoreId { get; set; }
public int QuizId { get; set; }
public string Answer { get; set; }
public virtual Quiz Quiz { get; set; }
}
so i have this viewmodel
public class ScoreQuizViewModel
{
public Score Score { get; set; }
public Quiz Quiz { get; set; }
}
and make this controller
public ActionResult Details(int id = 0)
{
Quiz quiz = db.Quizs.Find(id);
if (quiz == null)
{
return HttpNotFound();
}
return View(new ScoreQuizViewModel());
}
the problem is, theres nothing shown on my view
im using
#model SeedSimple.Models.ScoreQuizViewModel
and accessing with
#Html.DisplayFor(model => model.Quiz.Content)
i can see the result if im not using viewmodel.
how i can fix this?

It appears you're never filling in your ScoreQuizViewModel your code should look like this:
public ActionResult Details(int id = 0)
{
Quiz quiz = db.Quizs.Find(id);
if (quiz == null)
{
return HttpNotFound();
}
return View(new ScoreQuizViewModel { Quiz = quiz });
}

Related

generate a list of products of a category

I am developing a shop application and I need to show products of each category. The problem is each product is created from a product template which is stored in a table and each template is related to a category. here is the product model:
namespace fardashahr.Models
{
[Table("Product")]
public class ProductModel
{
public ProductModel()
{
if (Specs == null)
{
Specs = new Dictionary<string, SpecItemsModel>();
}
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public int ProductTemplateId { get; set; }
[Required]
public bool IsPublished { get; set; }
[Required]
public bool InStock { get; set; }
[Range(95, 110)]
public float SyncRate { get; set; }
public DateTime? ProductionDate { get; set; }
[Required]
public DateTime RegisterationDate { get; set; }
public string ImageName { get; set; }
public IEnumerable<string> GalleryImages { get; set; }
[NotMapped]
public Dictionary<string, SpecItemsModel> Specs { get; set; }
[ForeignKey("ProductTemplateId")]
public virtual ProductTemplateModel ProductTemplate { get; set; }
[ForeignKey("ManufacturerId")]
public virtual CodingItemModel Manufacturer { get; set; }
[ForeignKey("BrandId")]
public virtual CodingItemModel Brand { get; set; }
[ForeignKey("ModelId")]
public virtual CodingItemModel Model { get; set; }
[ForeignKey("SeriesId")]
public virtual CodingItemModel Series { get; set; }
}
}
and here is the the ProductTemplate:
namespace fardashahr.Models
{
[Table("ProductTemplate")]
public class ProductTemplateModel
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[StringLength(500)]
public string Name { get; set; }
[Required]
public int CategoryId { get; set; }
[StringLength(500)]
public string Description { get; set; }
[ForeignKey("CategoryId")]
public virtual CategoryModel Category{ get; set; }
}
}
and the controller is:
namespace fardashahr.Controllers
{
public class ProductsController : Controller
{
// GET: Products
public ActionResult Index()
{
return RedirectToAction("Index", "Home");
}
public ActionResult Category(string name)
{
//declare a list of products
List<ProductModel> productList;
using(MainModel db = new MainModel())
{
//get category id
CategoryModel category = db.Categories.Where(x => x.CategorytUrl == name).FirstOrDefault();
int catId = category.Id;
//initialize the list
productList = db.Products.Where(x => x. == catId).ToList();
}
}
}
}
finaly, what I want to know is how to initialize a list of products.
In your models, you added virtual keyword which indicates that navigation property will be automatically loaded without the need of LINQ lambda .include() expression.
Hence you can immediately access the navigation property and load the list like this;
productList = db.Products.Where(x => x.ProductTemplate.CategoryId == catId).ToList();
string categoryNameOfFirstProduct = productList.FirstOrDefault().ProductTemplate.Category.Name;
string categoryNameOfFirstProduct = productList.FirstOrDefault().ProductTemplate.Category.CategorytUrl;

How to include another table to view its data in Views in asp.net mvc

I have this code -
var add = (from h in db.Hotels
where h.Address.Contains(hotels.Address)
select h).Take(2);
ViewBag.Related = add;
Now, in the View, I want to display the images, so I'm using this code -
<img src="~/img/#item.FirstOrDefault().Image" />
This is giving me this error -
'System.Data.Entity.DynamicProxies.Hotels_D1EE6FD2E11BD1D9436F26FEA6336CFE76F33C59111E2ABC7C1BBE456FF61C23' does not contain a definition for 'FirstOrDefault'
I've tried using 'joins' also but same error occurs. Please help me out in this! :(
My Hotels class -
public class Hotels
{
[ScaffoldColumn(false)]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Address { get; set; }
[StringLength(8)]
public string PinCode { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string FilledBy { get; set; }
public DateTime DateAdded { get; set; }
//public int ImageId { get; set; }
public int TotalRooms { get; set; }
public bool Available { get; set; }
public virtual ICollection <Rooms> Rooms { get; set; }
public virtual ICollection <Images> Images { get; set; }
public virtual ICollection<Ameneties> Ameneties { get; set; }
public virtual ICollection <Bookings> Bookings { get; set; }
public virtual ICollection<NearByLocations> Nearby { get; set; }
public virtual ICollection<Ratings> Ratings { get; set; }
public virtual ICollection<RoomType> RoomTypes { get; set; }
public virtual ICollection<CustomerReviews> Reviews { get; set; }
public virtual ICollection<HotelRules> HotelRules { get; set; }
}
My Images class -
public class Images
{
[ScaffoldColumn(false)]
public int id { get; set; }
public string Image { get; set; }
public int? HotelId { get; set; }
public virtual Hotels Hotels { get; set; }
//public ICollection<Hotels> Hotels { get; set; }
}
I have used this type of collections...
This is my Details View Controller code -
public ActionResult Details(int? id)
{
IEnumerable<Images> galleries = (from gallery in db.Images
where gallery.Hotels.Id == id
select gallery);
ViewBag.Images = galleries;
ViewBag.ImgCount = galleries.Count();
IEnumerable<Ameneties> ameneties = (from a in db.Ameneties
where a.Hotels.Id == id
select a);
ViewBag.Ameneties = ameneties;
IQueryable<Rooms> rooms = (from room in db.Rooms
where room.Hotels.Id == id
select room);
var ratings = (from rating in db.Ratings
where rating.Hotels.Id == id
select rating.Points);
ViewBag.Ratings = ratings;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Hotels hotels = db.Hotels.Find(id);
if (hotels == null)
{
return HttpNotFound();
}
var add = db.Hotels.Include("Images").Where(h => h.Address.Contains(hotels.Address))
.Select(h => h)
.Take(2)
.ToList();
var model = new MyViewModel { Hotels = add };
ViewBag.Reviews = hotels.Reviews;
ViewBag.Ratings = hotels.Ratings;
ViewBag.NearBy = hotels.Nearby;
ViewBag.RoomTypes = hotels.RoomTypes;
ViewBag.Rules = hotels.HotelRules;
return View(hotels);
}
Could you add ToList() at the end of the query?
var add = (from h in db.Hotels
where h.Address.Contains(hotels.Address)
select h).Take(2)
.ToList();
ViewBag.Related = add;
Then you could call item.Images.FirstOrDefault()?.Image.
#foreach (var item in ViewBag.Related)
{
<img src="~/img/#item.Images.FirstOrDefault().Image" />
}
If it still doesn't work, you will need to explicitly load Image when you query Hotel. For example,
public IActionResult Index()
{
var add = db.Hotels
.Include("Images")
.Where(h => h.Address.Contains(hotels.Address))
.Select(h => h)
.Take(2)
.ToList();
var model = new MyViewModel { Hotels = add };
return View(model);
}
View
#model YourNameSpace.Models.MyViewModel
#foreach (var item in Model.Hotels)
{
<img src="~/img/#item.Images.FirstOrDefault().Image" />
}
Model
public class MyViewModel
{
public List<Hotels> Hotels { get; set; }
}

How to make single view using viewmodel in asp.net mvc 4?

I have different models Image,Page & PageCategories
public class Image
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
}
public class Page
{
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public virtual PageCategory PageCategory { get; set; }
}
public class PageCategory
{
public int PageCategoryId { get; set; }
public string CategoryName { get; set;
public virtual ICollection<Page> Pages { get; set; }
}
DBContext Class is
class DemoContext:DbContext
{
public DbSet<PageCategory> PageCategories { get; set; }
public DbSet<Page> Pages { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
I am wondering how to get all the model data to the home page using ViewModel.
For Ex.:
How to get image list and Page list in home page from multiple models?
You may want something like this :
viewModel :
//Create a viewModel with all the properties that you need
public class ViewModel
{
public int ImageId { get; set; }
public string ImageTitle { get; set; }
public string ImageURL { get; set; }
public int PageId { get; set; }
public string PageTitle { get; set; }
public string Content { get; set; }
public int PageCategoryId { get; set; }
public string CategoryName { get; set; }
}
Controller :
...
using (DemoContext db = new DemoContext()){
List<ImagePageViewModel> viewData = (from p in db.Page
join pc from db.PageCategory on p.PageCategoryId equals pc.PageCategoryId
select new ViewModel(){
PageTitle=p.PageTitle,
CategoryName = pc.CategoryName
//... set every property you want
})
}
return View(viewData );
note: I didn't add Image to the query because there is no explicit relation
between Image and the others table so i let you do it.
Create another class and define all above three into it. like below
public class MyView
{
public List<Image> Images { get; set; }
public List<Page> Pages { get; set; }
public List<PageCategory> PageCategories { get; set; }
}
Controller Action:-
public ActionResult Index()
{
MyView myView = // Get it using your logic
return View(myView);
}
finally got my answer:
public class ViewModelDemo
{
public IEnumerable<Image> images { get; set; }
public IEnumerable<Pages> pages { get; set; }
public IEnumerable<PageCategory> pagecategories { get; set; }
}
Then in HomeController
private DemoContext db=new DemoContext();
public ActionResult Index()
{
ViewModelDemo vm = new ViewModelDemo();
vm.images = db.Images.ToList();
vm.pages=db.Pagess.ToList();
vm.pagecategories=db.PageCategories.ToList();
return View(vm);
}

ASP.NET MVC 4 Code First Many to Many Adding to Collection

I am using ASP.NET MVC 4 code first pattern for database layer. I have a many to many relationship between UserProfile and Task. When I try to add a task to the the collection of tasks of a user, it's added but if I try to query it and see if it's there it's not showing up.
My model:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string SirName { get; set; }
public string Position { get; set; }
public string Email { get; set; }
public ICollection<TaskModels> Tasks {get; set; }
public bool? isActive { get; set; }
public UserProfile()
{
Tasks = new HashSet<TaskModels>();
}
}
public class TaskModels
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public ICollection<UserProfile> Employees { get; set; }
public int TimeNeeded { get; set; }
public int TimeWorked { get; set; }
public string Status { get; set; }
public bool isActive { get; set; }
public TaskModels()
{
Employees = new HashSet<UserProfile>();
}
}
public class WorkLogModels
{
public int Id { get; set; }
public UserProfile Author { get; set; }
public DateTime TimeBeganWorking { get; set; }
public int TimeWorkedOn { get; set; }
public TaskModels Task { get; set; }
public string Description { get; set; }
}
public class TimeTrackerDb : DbContext
{
public TimeTrackerDb() : base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<TaskModels> Tasks { get; set; }
public DbSet<WorkLogModels> WorkLogs { get; set; }
}
I try to check if a UserProfile already exists in a Task's Employees list and it's always empty.
[HttpPost]
public ActionResult Create(WorkLogModels worklogmodels)
{
var tasks = db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).SingleOrDefault();
if (tasks == null)
{
return View(worklogmodels);
}
if (ModelState.IsValid)
{
var user = db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
var task = db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).FirstOrDefault();
WorkLogModels log = new WorkLogModels();
log.Description = worklogmodels.Description;
log.TimeBeganWorking = worklogmodels.TimeBeganWorking;
log.TimeWorkedOn = worklogmodels.TimeWorkedOn;
log.Author = user;
log.Task = task;
db.WorkLogs.Add(log);
if (!db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).First().Tasks.Any(x=> x.Name == worklogmodels.Task.Name))
{
db.UserProfiles.Where(x => x.UserId == WebSecurity.CurrentUserId).FirstOrDefault().Tasks.Add(task);
db.Tasks.Where(x => x.Name == worklogmodels.Task.Name).FirstOrDefault().Employees.Add(user);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(worklogmodels);
}
I've been fighting with this for two days now.
Any help will be greatly appreciated
EDIT:
I am not sure if I made myself clear. In the Crate action for the WorkLog Controller I am trying to put the current user in the current task's collection and vice versa. It works correctly the first time, but then if I do it again it fails to skip the if statement and tries to add it once again and throws an exception : System.Data.SqlClient.SqlException. It's trying to add the same record to the intermediate table.

Help understanding the basics of AutoMapper

So I have this two classes:
public class PhysicalTest
{
public int ID { get; set; }
public DateTime CreationDate { get; set; }
public int Weight { get; set; }
public int Height { get; set; }
public int Systolic { get; set; }
public int Diastolic { get; set; }
public int Pulse { get; set; }
}
public class PhysicalTestFormViewModel
{
public int ID { get; set; }
public DateTime CreationDate { get; set; }
[Required]
public int Weight { get; set; }
[Required]
public int Height { get; set; }
public int Systolic { get; set; }
public int Diastolic { get; set; }
public int Pulse { get; set; }
}
This is my AutoMapper configuration
Mapper.CreateMap<PhysicalTestFormViewModel, PhysicalTest>();
When I do this it works just fine
[HttpPost]
public ActionResult Create(int ehrId, PhysicalTestFormViewModel physicaltestvm)
{
EHR ehr = ehrRepository.Find(ehrId);
if (ehr.UserName != User.Identity.Name)
return View("Invalid Owner");
if (ModelState.IsValid)
{
PhysicalTest physicalTest= new PhysicalTest();
Mapper.Map(physicaltestvm, physicalTest);
physicalTest.PerformedBy = "Yo";
physicalTest.CreationDate = DateTime.Now;
ehr.PhysicalTests.Add(physicalTest);
ehrRepository.Save();
return RedirectToAction("Index");
}
else
{
return View(physicaltestvm);
}
}
But when I do this I get an error
Trying to map Summumnet.PhysicalTest
to
Summumnet.ViewModels.PhysicalTestFormViewModel.
Missing type map configuration or
unsupported mapping. Exception of type
'AutoMapper.AutoMapperMappingException'
was thrown.
public ActionResult Edit(int ehrId, int id)
{
EHR ehr = ehrRepository.Find(ehrId);
if (ehr.UserName != User.Identity.Name)
return View("Invalid Owner");
var physicalTest = ehr.PhysicalTests.Where(test => test.ID == id).Single();
PhysicalTestFormViewModel physicaltestvm = new PhysicalTestFormViewModel();
Mapper.Map(physicalTest, physicaltestvm);
return View(physicaltestvm);
}
In the scenario where the error is thrown I simply want to construct an ViewModel to display an Edit form.... what is the standard way of doing this?
You have only defined a mapping from PhysicalTestFormViewModel to PhysicalTest:
Mapper.CreateMap<PhysicalTestFormViewModel, PhysicalTest>();
You also need the opposite one:
Mapper.CreateMap<PhysicalTest, PhysicalTestFormViewModel>();
See this related SO question and answers.
you may do dynamic mapping where you dont have to create any maps
public ActionResult (PhysicalTestFormViewModel ptvm)
{
//other to wrote codes
EHR ehr = ehrRepository.Find(ehrId);
AutoMapper.Mapper.DynamicMap<PhysicalTestFormViewModel, PhysicalTest>(ptvm, ehr);
db.SaveChanges();
}

Resources