Asp.net ViewModel returning null - c#

I am fairly new to Asp.Net Mvc5 as well as c# and I am hoping to acquire a few pointers here, I have been trying to figure out why I was getting the following error :
The model item passed into the dictionary is of type 'System.Data.Entity.DbSet1[SoccerTeams.Models.Player]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[SoccerTeams.Models.ViewModels.TeamViewModel]'.
However now after debugging I realized that the ViewModel object is actually returning null values for all the items. I have created a page that works correctly for adding a team as well as players for that team. In my database the teams has one table and all the players are in another table which each player has the teams name with it (player and team name are in two separate columns) so it can be associated with the correct team. I have created a ViewModel and I am attempting to call that ViewModel and be able to return all the players to the view so I can show them in a list.
My Team controller for the "View all players view" is as follows:
public ActionResult ViewAllPlayers()
{
TeamViewModel teamView = new TeamViewModel();
return View(teamView);
}
My Team Model is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SoccerTeams.Models
{
// This teams class will be used to represent the teams in the database
public class Team
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string TeamName { get; set; }
public string Coach { get; set; }
public string Conference { get; set; }
}
}
My Player Model is as follows:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SoccerTeams.Models
{
public class Player
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Guid TeamId { get; set; }
public string Name { get; set; }
}
}
My ViewModel is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SoccerTeams.Models.ViewModels
{
public class TeamViewModel
{
public string TeamName { get; set; }
public string Coach { get; set; }
public string Conference { get; set; }
public List<Player> Players { get; set; }
}
}
My CreateTeam action is as follows:
public async Task<ActionResult> Create(TeamViewModel model, string addfiverows)
{
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(addfiverows)) return View(model);
var team = new Team { TeamName = model.TeamName, Coach = model.Coach, Conference = model.Conference };
db.Teams.Add(team);
var result = await db.SaveChangesAsync();
if(result > 0)
{
foreach(var player in model.Players)
{
var p = new Player { Name = player.Name, Id = team.Id };
db.Players.Add(p);
}
result = await db.SaveChangesAsync();
}
if(result > 0) return RedirectToAction("Index");
}
return View();
}
My View I am trying to display on is as follows:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model SoccerTeams.Models.ViewModels.TeamViewModel
#{
ViewBag.Title = "View All Players";
}
<h2>View All Players</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.TeamName)
</th>
<th>
#Html.DisplayNameFor(model => model.Players)
</th>
<th></th>
</tr>
#foreach (var item in Model.Players)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.TeamName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Players)
</td>
</tr>
}
</table>
From researching I thought the problem had something to do with the #model IEnumerable<SoccerTeams.Models.ViewModels.TeamViewModel>. However after talking with #Tony Bao challenging my understanding I noticed that the Viewmodel is actually returning the fields however with null values.
I am also seeking any guides or tutorials as I am not only looking for a solution but also a better understanding of why this happens and how to use the ViewModel properly.

First add Player collection to Team model:
public class Team
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string TeamName { get; set; }
public string Coach { get; set; }
public string Conference { get; set; }
public virtual ICollection<Player> Players { get; set; }
}
and in Player model add Team:
public class Player
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string Name { get; set; }
public Guid TeamId { get; set; }
public virtual Team Team {get; set;}
}
and in ViewAllPlayers action:
public ActionResult ViewAllPlayers(Guid id)
{
var team = db.Teams.Include(t => t.Players).Single(t => t.Id == id);
TeamViewModel teamView = new TeamViewModel
{
TeamName = team.TeamName,
Coach = team.Coach,
Conference = team.Conference,
Player = new List<Player>(team.Players)
};
return View(teamView);
}

You can view DisplayFor Templates in your scenario. There are tons of materials on displaytemplates(for display) and editortempates(for insert and update). you can search on google
Here what i will propose
public ActionResult ViewAllPlayers()
{
//this should be from your database
var teamviewer = new TeamViewModel();
teamviewer.TeamName = "t1";
teamviewer.Players = new List<Player>() { new Player { PlayerName = "p1" }, new Player { PlayerName = "p2" } };
return View();
}
Your view Models
public class TeamViewModel
{
public string TeamName { get; set; }
public string Coach { get; set; }
public string Conference { get; set; }
public List<Player> Players { get; set; }
}
public class Player
{
public string PlayerName { get; set; }
}
Create a Displayfor template here
Views/Shared/DisplayTemplates/Player.cshtml
Player.cshtml
#model SoccerTeams.Models.Player
#Html.DisplayFor(m=>m.PlayerName)
On your index page
#model SoccerTeams.Models.TeamViewModel
<h2>View All Players</h2>
<table class="table">
<tr>
<td>
#Html.DisplayFor(modelItem => modelItem.TeamName)
</td>
<td>
#Html.DisplayFor(modelItem=>modelItem.Players)
</td>
</tr>
</table>

Related

Return related table data in MVC view

I'm creating a golf app to store all my rounds of golf and what I have scored.
I am getting an error with the RoundViewModel and the ScoreViewModel where I get the following error,
Error CS1061 'RoundViewModel' does not contain a definition for
'Score' and no accessible extension method 'Score' accepting a first
argument of type 'RoundViewModel' could be found (are you missing a
using directive or an assembly reference?)
The code for the create.
public ActionResult Create()
{
//Get database values
var dbcourse = db.Course.ToList();
//Make selectlist, which is IEnumerable<SelectListItem>
var courseNameDropdownList = new SelectList(db.Course.Select(item => new SelectListItem()
{
Text = item.CourseName.ToString(),
Value = item.CourseId.ToString()
}).ToList(), "Value", "Text");
// Assign the Selectlist to the View Model
var viewCourse = new RoundViewModel()
{
Course = dbcourse.FirstOrDefault(),
// The Dropdownlist values
CourseNamesDropdownList = courseNameDropdownList,
};
return View(viewCourse);
}
The code for the RoundViewModel.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace GolfScore.Models
{
public class RoundViewModel
{
[Key]
public int RoundId { get; set; }
[Display(Name = "Round")]
public int RoundNumber { get; set; }
[Display(Name = "Date round played")]
[DataType(DataType.DateTime)]
public DateTime DateTime { get; set; }
public int? CourseId { get; set; }
public virtual CourseViewModel Course { get; set; }
public IEnumerable<SelectListItem> CourseNamesDropdownList { get; set; }
}
}
the code for the ScoreViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace GolfScore.Models
{
public class ScoreViewModel
{
[Key]
public int ScoreId { get; set; }
[Range(1 , 20)]
public int ScoreTotal { get; set; }
public int? HoleId { get; set; }
public virtual HoleViewModel Hole { get; set; }
public int? RoundId { get; set; }
public RoundViewModel Round { get; set; }
}
}
and the code for the create view
<dd class="col-sm-10">
<table class="table">
<tr>
<th>Hole</th>
<th>Par</th>
<th>Score</th>
</tr>
#foreach (var item in Model.Course.Holes)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.HoleNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.Par.ParNumber)
</td>
<td>
#Html.DisplayFor(model => Model.Score.ScoreTotal )
<div class="col-md-10">
#Html.EditorFor(model => Model.Score.ScoreTotal, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => Model.Score, "", new { #class = "text-danger" })
</div>
</td>
</tr>
}
</table>
</dd>
I have tried amending the RoundViewModel to include
public int? ScoreId { get; set; }
public virtual ScoreViewModel Score { get; set; }
but this causes the following error:
Unable to determine the principal end of an association between the
types 'GolfScore.Models.ScoreViewModel' and
'GolfScore.Models.RoundViewModel'. The principal end of this
association must be explicitly configured using either the
relationship fluent API or data annotations.'
Any help on how I can get the related score data into my create view is appreciated.
The following error:
Unable to determine the principal end of an association between the types 'GolfScore.Models.ScoreViewModel' and 'GolfScore.Models.RoundViewModel'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.'
Is happening because you're using one to one relationship without specifying which end is the principal in the relationship.
Add a [Required] attribute on the attribute in which you're considering a principal in the relationship.
In your case I think it should be in the ScoreViewModel class. Which mean your class should be like this now:
public class ScoreViewModel
{
[Key]
public int ScoreId { get; set; }
[Range(1 , 20)]
public int ScoreTotal { get; set; }
public int? HoleId { get; set; }
public virtual HoleViewModel Hole { get; set; }
public int? RoundId { get; set; }
[Required]
public RoundViewModel Round { get; set; }
}

ASP.NET MVC Many-to-many relationship with viewmodel

I'm trying to display a list of books that will show the details for each book. It all works properly, except for the properties which have many-to-many relationships with the Books model.
Here is my Book model (I removed annotations for readability):
public class Book
{
public int BookId { get; set; }
public string title { get; set; }
public Int32 isbn { get; set; }
public string author { get; set; }
public string summary { get; set; }
public string series { get; set; }
public string amazonLink { get; set; }
public string pubLink { get; set; }
public int? GradeLevelId { get; set; } //Foreign Key for GradeLevel
public bool needsEdit { get; set; }
public int? LexileLevelId { get; set; } //Foreign Key for LexileLevel
public DateTime dateAdded { get; set; }
public Book()
{
dateAdded = DateTime.Now;
}
public string comments { get; set; }
public virtual GradeLevel GradeLevel { get; set; }
public virtual LexileLevel LexileLevel { get; set; }
//Navigation Properties
public virtual ICollection<Recommendation> Recommendations { get; set; }
public virtual ICollection<RelevantGenre> RelevantGenres { get; set; }
}
The two navigation properties (Recommendation and RelevantGenre) are for the associative/joining tables, and that's where I'm having issues. To keep things simple, I'm going to focus on the RelevantGenre model. Each book can have more than one Genre, so the RelevantGenre is the join table between Book and Genre.
Here's the Model for those:
public class RelevantGenre
{
//Both are primary keys
[Key]
[Column(Order = 1)]
public int BookId { get; set; } //Foreign Key to Book
[Key]
[Column(Order = 2)]
public int genreId { get; set; } //Foreign Key to Genre
public virtual Book Book { get; set; } //Nav property
public virtual Genre Genre { get; set; } //Nav property
}
public class Genre
{
public int GenreId { get; set; }
public string genreTitle { get; set; }
public int genreOrder { get; set; }
//Navigation Property to RelevantGenre
public ICollection<RelevantGenre> RelevantGenres { get; set; }
}
Here's the Controller:
// GET: Books
public ActionResult Index(string filter, string searchString)
{
var viewModel = new BookListViewModel();
if (String.IsNullOrEmpty(searchString) && String.IsNullOrEmpty(filter))
{
var results = from b in db.Books select b;
var resultsList = (results.ToList());
viewModel.Books = resultsList;
return View(viewModel);
}
else
{
var results = from b in db.Books select b;
//Filtering the book list
switch (filter)
{
case "HR":
results = from b in db.Books
join r in db.Recommendations
on new { b.BookId } equals
new { r.BookId }
where (r.RecommendationTypeId == 1)
select b;
break;
default:
results = from b in db.Books select b;
break;
}
if(!String.IsNullOrEmpty(searchString))
{
//Search query results
var searchResults = from b in db.Books
.Where(model => model.title.Contains(searchString) || model.author.Contains(searchString)
|| model.series.Contains(searchString))
select b;
if (searchResults != null )
{
results = searchResults;
}
else
{
ViewBag.SpanText = "Sorry, no results founds. Please try your search again.";
}
}
var resultsList = (results.ToList());
viewModel.Books = resultsList;
return View(viewModel);
}
}
As you can see, it's returning a viewModel, because I thought that made the most sense for how to return a combination of model data.
Here's the viewmodel:
public class BookListViewModel
{
public List<Book> Books { get; set; }
public int BookId { get; set; }
public string title { get; set; }
public string author { get; set; }
public Int32 isbn { get; set; }
public string series { get; set; }
public int? GradeLevelId { get; set; }
public string gradeLevelName { get; set; }
public int? LexileLevelId { get; set; }
public string lexileLevelName { get; set; }
public Recommendation Recommendation { get; set; }
public int RecommendationTypeId { get; set; }
public string recName { get; set; }
public RelevantGenre RelevantGenre { get; set; }
public int genreId { get; set; }
}
And lastly, here's the view:
#model FavBooks.ViewModels.BookListViewModel
#{
ViewBag.Title = "All Books";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Books</h2>
<p class="details">
#Html.ActionLink("Browse All Books in List Format", "FullList", "Books")
</p>
#foreach (var item in Model.Books)
{
<div class="row fullBorder">
<div class="col-md-2 col-sm-2">
<img src="~/Content/Images/harrypotterbook.png" class="bookThumb" alt="Book Image" />
</div>
<div class="col-md-3 col-xs-3">
<h3>
<a href="#Url.Action("Details", "Books", new { id = item.BookId })" class="darkLink bookTitle">
#Html.DisplayFor(modelItem => item.title)
</a>
</h3>
<h4>By #Html.DisplayFor(modelItem => item.author)</h4>
<p><strong>ISBN:</strong> #Html.DisplayFor(modelItem => item.isbn)</p>
</div>
<div class="col-md-3 col-sm-4 bookMargins">
#{
if (item.series != null)
{
<p><strong>Series:</strong> #Html.DisplayFor(modelItem => item.series) </p>
}
else
{
<p></p>
}
}
<p><strong>Grade Level:</strong> #Html.DisplayFor(modelItem => item.GradeLevel.gradeLevelName )</p>
<p><strong>Lexile Level:</strong> #Html.DisplayFor(modelItem => item.LexileLevel.lexileLevelName)</p>
</div>
<div class="col-md-4 col-sm-3">
#Html.ActionLink("View Book Details", "Details", "Books", new { id = item.BookId }, new { #class="btn btn-default btnBookDetails" })
</div>
</div>
}
You can see that my view displays a list of items from Model.Books using a foreach loop. For each book, I'd like it to also display the RelevantGenres that are connected to the book, but it's not letting me. The GradeLevel and LexileLevel properties connect just fine (those are one-to-many), but it doesn't seem to register any of the many-to-many relationships which are not directly part of the Book model.
I feel like I'm missing something basic here, or maybe there's an issue with my view-model setup. Do you see where I went wrong on this or what I can do to display each book's genres?
EDIT:
Let me get more specific with what I tried.
I saw here that it's possible to use a foreach inside of another foreach to display a loop. But when I try that, it tells me that the "foreach cannot operate on that... because Favbooks.Models.Book does not contain a public definition for GetEnumerator". So I tried changing the #model to an IEnumerable<> and looping through the whole Model (instead of foreach(var item in Model.Books) but then it still wouldn't work. In that situation, it gave me an error saying:
'BookListViewModel' does not contain a definition for 'RelevantGenres' and no extension method 'RelevantGenres' accepting a first argument of type 'BookListViewModel' could be found (are you missing a using directive or an assembly reference?)
Because that wasn't working, I kept the #model with #model FavBooks.ViewModels.BookListViewModel like it was initially, and and tried putting in #Html.DisplayFor(modelItem => item.Genres.genreTitle) but it doesn't recognize Genre or RelevantGenre.
To sum up, the issue is that if I loop through Model.Books, then it won't recognize anything in the viewmodel other than the Books list. But if I loop through the overall Model, then it still won't recognize the RelevantGenres, and now it started giving me another error like this:
The model item passed into the dictionary is of type 'FavBooks.ViewModels.BookListViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[FavBooks.ViewModels.BookListViewModel]'.
I'm sorry if this isn't totally clear. I haven't worked so much with viewmodels before and I see that I must have set it up wrong, but I just don't know how to get this working...
Have you tried .Include()? This will populate all the related data in the navigation property. Refer https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application for more detials.
eg:
var BookList = _context.Book.Where(m=>m.BookId==id).Include(m=>m.Recommendations).Include(m=>m.RelevantGenres)
This will query a record of Book whose BookId=id and will populate all the related navigation properties.
There's also .ThenInclude()
A property of public List<Book> Books { get; set; } should be enough as this will store all the data related to your retrieved entity.
and below is example of how you can access the fields of a navigation property.
#model BookListViewModel
foreach(var b in Model.Books)
{
#HtmlDisplayFor(modelItem=>b.title)
foreach(var r in b.RelevantGenres)
{
#HtmlDisplayFor(modelItem=>r.GenereName)
}
}
Myself being fairly new to .netcore mvc, I don't know much either. But I hope this helps to point you in the right direction if not completely solve your issue.

Displaying data from multiple models on one view (images and text)

Hi everyone so I am trying to create an application using asp.net mvc with a code first database that allows the users to be able to create a blog post with as many images as they wish.I have the data stored in the database but I I am currently trying to have the the head, body and images displaying in the display view this is what I would like it to look like : http://imgur.com/a/IR19r but I am not sure how to accomplish this. I am able to display the head and body but cannot get the images from the image table here is the database diagram: http://imgur.com/a/lvwti
Currently this is the error I get when i add this to the view #Html.DisplayFor(modelItem => item.Images)
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: An error occurred while executing the command definition. See the inner exception for details.
Model
public partial class PostModel
{
public PostModel()
{
Images = new List<ImageModel>();
}
[Key]
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[Required(ErrorMessage = "Heading is Required")]
[Display(Name = "Heading")]
public string Heading { get; set; }
[Required(ErrorMessage = "Body is Required")]
[DataType(DataType.MultilineText)]
[Display(Name = "Body")]
public string Body { get; set; }
public virtual ICollection<ImageModel> Images { get; set; }
public IEnumerable<HttpPostedFileBase> File { get; set; }
}
public class ImageModel
{
[Key]
public int ID { get; set; }
public string Path { get; set; }
public virtual PostModel Post { get; set; }
public string DisplayName { get; set; }
}
public class ImageVM
{
public int? ID { get; set; }
public string Path { get; set; }
public string DisplayName { get; set; }
public bool IsDeleted { get; set; }
}
public partial class PostVM
{
public PostVM()
{
Images = new List<ImageVM>();
}
public int? ID { get; set; }
public string Heading { get; set; }
public string Body { get; set; }
public IEnumerable<HttpPostedFileBase> Files { get; set; }
public List<ImageVM> Images { get; set; }
}
DbContext
public class EFDbContext : DbContext
{
public DbSet<PostModel> Posts { get; set; }
public DbSet<PostVM> PostVMs { get; set; }
public DbSet<ImageModel> Images { get; set; }
public DbSet<ImageVM> ImageVMs { get; set; }
}
Controller
public ViewResult Display()
{
return View(repository.Posts)
}
View
#model IEnumerable<Crud.Models.PostModel>
#{
ViewBag.Title = "Index";
}
#foreach (var item in Model)
{
<div>
#Html.DisplayFor(modelItem => item.Heading)
</div>
<div>
#Html.DisplayFor(modelItem => item.Body)
</div>
<div>
#Html.DisplayFor(modelItem => item.Images)
#*<img class="img-thumbnail" width="150" height="150" src="/Img/#item.Images" />*#
</div>
}
Here is alternative controller I tried but am not using as I got this error when i tried let Images = i.Path and wasn't really sure if this was meant to be how it was done
Cannot implicity convert typeCrud 'string' to 'System.Collections.Generic.List Crud.Models.ImageVm '
public ViewResult Display()
{
IEnumerable<PostVM> model = null;
model = (from p in db.Posts
join i in db.Images on p.ID equals i.Post
select new PostVM
{
ID = p.ID,
Heading = p.Heading,
Body = p.Body,
Images = i.Path
});
return View(model);
}
item.Images is a collection. So loop through that and display the images.
<div>
#foreach(var image in item.Images)
{
<img src="#image.Path" />
}
</div>
You need to make changes to the src property depending on what value you store in the Path property of image.
You can correct your other action method like this
public ViewResult Display()
{
var posts = db.Posts.Select(d => new PostVM()
{
ID = d.ID ,
Heading = d.Heading,
Body = d.Body,
Images = d.Images.Select(i => new ImageVM() { Path = i.Path,
DisplayName = i.DisplayName }
).ToList()
}).ToList();
return View(posts);
}
Now since you are returning a list of PostVM, make sure your Display view is strongly typed to that.
#model List<PostVM>
<h1>Posts</h1>
#foreach(var p in Model)
{
<h3>#p.Heading</h3>
<p>#p.Body</p>
#foreach(var image in item.Images)
{
<img src="#image.Path" />
}
}
Also, there is no point in keeping the view model classes on your db context. Keep only your entity models. View models are only for the use of UI layer.
public class EFDbContext : DbContext
{
public DbSet<PostModel> Posts { get; set; }
public DbSet<ImageModel> Images { get; set; }
}

How to save data dynamically from a View in MVC5

I want to build a Questionnaire MVC5 project.
I have a MSSQL database with several tables like: Employee, Questions, Results ...
I made a new MVC5 project, I add it the model base on my database and I manage all CRUD operations need it.
Now I made an view for Questionar :
#model IEnumerable<ChestionarMVC.Models.FormQuestion>
#{
ViewBag.Title = "Chestionar";
}
<h2>Chestionar</h2>
#foreach (var item in Model)
{
#Html.Partial("_Chestionar",item)
}
<input id="Submit1" type="submit" value="submit" />
And a partialView to show each question with 2 text area, one for the answer and one for some aditional info :
#model ChestionarMVC.Models.FormQuestion
<table border="1" style="width:100%">
<tr>
<td>
#Html.DisplayFor(modelItem => Model.Question)
</td>
</tr>
<tr>
<td>
Raspuns <br />
<textarea id="TextArea1" rows="2" cols="80" style="width:800px; height:100px;"></textarea>
</td>
</tr>
<tr>
<td>
Document <br />
<textarea id="TextArea2" rows="2" cols="80" style="width:400px"></textarea>
</td>
</tr>
</table>
Now I want to save in the tblResults the QuestionID, Answer and Document.
In webforms I made a usercontrol, then I used Foreach usercontrol , and saved to database.
In MVC how can I save all?
This is the QuestionsModel:
namespace ChestionarMVC.Models
{
using System;
using System.Collections.Generic;
public partial class FormQuestion
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public FormQuestion()
{
this.FormResults = new HashSet<FormResult>();
this.TBLPos = new HashSet<TBLPos>();
}
public int idQuestion { get; set; }
public string Question { get; set; }
public int idCategory { get; set; }
public int idPosition { get; set; }
public Nullable<int> Ordine { get; set; }
public virtual FormCategory FormCategory { get; set; }
public virtual Formular Formular { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<FormResult> FormResults { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TBLPos> TBLPos { get; set; }
}
}
this is the ResultsMOdel:
namespace ChestionarMVC.Models
{
using System;
using System.Collections.Generic;
public partial class FormResult
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public FormResult()
{
this.Documentes = new HashSet<Documente>();
}
public int idResult { get; set; }
public int idUser { get; set; }
public int idQuestion { get; set; }
public string Answer { get; set; }
public string RefferenceDocument { get; set; }
public Nullable<System.DateTime> StampDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Documente> Documentes { get; set; }
public virtual Employee Employee { get; set; }
public virtual FormQuestion FormQuestion { get; set; }
}
}
this is the Questionnaire ActionResult used to generate the Questionnaire-View:
public ActionResult Chestionar()
{
var formQuestions = db.FormQuestions;
return View(formQuestions.ToList());
}
Start by creating a view model containing the properties you want for the view (note add other validation attributes as required to suit your needs)
public class QuestionVM
{
public int ID { get; set; }
public string Question { get; set; }
[Required(ErrorMessage = "Please enter and answer")]
public string Answer { get; set; }
public string Document { get; set; }
}
Then create an EditorTemplate. In /Views/Shared/EditorTemplates/QuestionVM.cshtml
#model QuestionVM
#Html.HiddenFor(m => m.ID)
#Html.HiddenFor(m => m.Question)
#Html.DisplayNameFor(m => m.Question)
#Html.DisplayFor(m => m.Question)
#Html.LabelFor(m => m.Answer)
#Html.TextAreaFor(m => m.Answer)
#Html.ValidationMessageFor(m => m.Answer)
... // ditto for Document (as for Answer)
And in the main view
#model IEnumerable<QuestionVM>
#using (Html.BeginForm())
{
#Html.EditorFor(m => m)
<input type="submit" ... />
}
Note that the EditorFor() method will generate the html for each Question based on the template, and importantly will add the correct name attributes that enable your form controls to be posted back and bound to your model
The in the controller
public ActionResult Chestionar()
{
// Get data model and map to view models
var model = db.FormQuestions.Select(q => new QuestionVM()
{
ID = q.idQuestion,
Question = q.Question,
Answer = .....,
Document = .... // see notes below
};
return View(model);
}
[HttpPost]
public ActionResult Chestionar(IEnumerable<QuestionVM> model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Get the data model again, map the view model properties back to the data model
// update properties such as user and date
// save and redirect
}
Side note: your question indicates an (one) Answer and Document for each question, yet you current models for the Question have a collection (ICollection<FormResult> FormResults) containing properties for the Answer and RefferenceDocument so its not clear if you want to add multiple answers and documents for each Question, or just one.

Complex ViewModel - View cannot Automap values from model Advice Needed..

I have a complex View. It has data from 4 Models. The models are all static and work as expected. I have created a ViewModel to attempt to show just the data needed for this view. It is made up of Competitors and some complex Classes and Events they participate in.
I have made a complex ViewModel. When I walk through the Controller, I can see all three parts being constructed from the ViewModel. Its all there including data. When I try to map the values using Intellesense in the View, it has no way of knowing this data, or has no mapping from the complex ViewModel. Am I doing this right? I have tried several ways to map these values to the View. I think I need to initialize or map the values to the Models derived from, I just cannot figure out how.
Please advise on how to map these values, data elements to the view.
ViewModel:
Compeditor is an from an actual model direct to the DB
The rest of the data is gathered from multiple tables and passed to view from controller
namespace eManager.Web2.Models
{
public class CompDetailPlus
{
public CompDetailPlus()
{
this.Compeditor = new Compeditor();
}
public virtual Compeditor Compeditor { get; set; }
public virtual IEnumerable<InEventClass> InEventClass { get; set; }
public virtual IEnumerable<AllEventClasses> AllEventClasses { get; set; }
}
public class Compeditor
{
[Key]
public virtual int CompeditorId { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual string MiddleInt { get; set; }
public virtual string StreetAddress { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual string PostalCode { get; set; }
public virtual string EmailAddress { get; set; }
public virtual string HomePhone { get; set; }
public virtual string CellPhone { get; set; }
public virtual double Height { get; set; }
public virtual double Weight { get; set; }
public virtual int Age { get; set; }
public virtual int Event_CompId { get; set; }
}
public class InEventClass
{
public virtual int EventClassID { get; set; }
public virtual string ClassName { get; set; }
public virtual bool IsSelected { get; set; }
}
//duplicate to simplify how the second list is pulled and then combined with first list
public class AllEventClasses
{
public virtual int EventClassID { get; set; }
public virtual string ClassName { get; set; }
public virtual bool IsSelected { get; set; }
}
}
Controller:
public ActionResult CompeditorDetail(int CompeditorId)
{
//Pull the Competitor detail for the ID passed in
var comp = _db.Compeditors.Single(c => c.CompeditorId == CompeditorId);
//Pull a list of Event-Classes the competitor is already signed up for on current event
var nlist = (from o in _db.Compeditors
join o2 in _db.Event_Class_Compeditors_s on o.CompeditorId equals CompeditorId
where o.CompeditorId.Equals(CompeditorId)
join o3 in _db.Event_Classes on o2.EventClassID equals o3.EventClassID
where o2.EventClassID.Equals(o3.EventClassID)
join o4 in _db.Class_Definitions on o3.ClassID equals o4.Class_Definition_ID
where o3.ClassID.Equals(o4.Class_Definition_ID)
select new InEventClass()
{
ClassName = o4.Class_Name,
EventClassID = o2.EventClassID,
IsSelected = true
}).ToList();
//pull a complete list of Event Classes that are avaiaible
var totallist = (from o in _db.Event_Classes
join o2 in _db.Event_Classes on o.ClassID equals o2.ClassID
where o.ClassID.Equals(o2.ClassID)
join o3 in _db.Class_Definitions on o2.ClassID equals o3.Class_Definition_ID
where o2.ClassID.Equals(o3.Class_Definition_ID)
join o4 in _db.Events on o.EventID equals o4.EventID
where o.EventID.Equals(o4.EventID)
where o4.CurrentEvent.Equals(true)
select new AllEventClasses()
{
ClassName = o3.Class_Name,
EventClassID = o2.EventClassID,
IsSelected = false
}).ToList();
var whatsleft = totallist.Where(eachtotalclass => !(nlist.Any(eachClassIHave => eachClassIHave.EventClassID == eachtotalclass.EventClassID))).ToList();
var model = new CompDetailPlus { AllEventClasses = whatsleft, Compeditor = comp, InEventClass = nlist };
return View(model);
}
View:
(Has to show the Competitor detail and a compound list of Event_Classes they are in)
In the view, I cannot see the values for any data.. all error on run and no good for display.
#model IEnumerable<eManager.Web2.Models.CompDetailPlus>
#{
ViewBag.Title = "Competitor's Detail";
}
<h2>#ViewBag.Title</h2>
<fieldset>
<legend>Compeditor</legend>
<table border="1" >
<tr>
<td>
<div class="display-field">
#Html.HiddenFor(model => model.Compeditor.CompeditorId)
</div>
<b>First Name</b>
<div class="display-field">
#Html.DisplayFor(model => model.Compeditor.FirstName)
</div>
</td>
<td>
<b>Last Name</b>
<div class="display-field">
#Html.DisplayFor(model => model.Compeditor.LastName)
</div>
</td>
#using (Html.BeginForm("CompeditorDetail", "Compeditor", FormMethod.Post))
{
foreach (var item in Model)
{
<input type="checkbox" name="MyID" value="#item.AllEventClasses.IsSelected"/> #item.InEventClass.ClassName <br />
<input type="hidden" name="CompeditorID" value="#item.InEventClass.CompeditorId" />
}
}
</td>
Your View accepts a model of IEnumerable eManager.Web2.Models.CompDetailPlus which would be fine, but your controller is sending a single eManager.Web2.Models.CompDetailPlus object.
Try changing this in your View
#model IEnumerable<eManager.Web2.Models.CompDetailPlus>
to this:
#model eManager.Web2.Models.CompDetailPlus
And change the bottom part of your view so that it's iterating through Enumerable compaosite items inside your model.

Categories