ASP.ET MVC 4 to view data from several tables ViewBag - asp.net-mvc

I need to output information from two tables
public class Team
{
[Key]
public int TeamId { get; set; }
public int TypeId { get; set; }
public string TeamName { get; set; }
}public class TeamType
{
[Key]
public int TypeId { get; set; }
public string TypeName { get; set; }
public virtual ICollection<Team> Teams { get; set; }
}
I build this class
public abstract class MyAppController : Controller
{
//
// GET: /MyApp/
private RenegadeEntities db = new RenegadeEntities();
public RenegadeEntities DataContext
{
get { return db; }
}
public MyAppController()
{
ViewBag.TeamList = db.TeamTypes.Include("Teams").ToList();
}
}
in view i do following:
#using Renegades.Helpers
#model IEnumerable<Renegades.Models.TeamType>
#foreach (var t in ViewBag.TeamList)
{
<li>
<span>#t.TypeName</span>
<ul id="sub_team_menu">
#foreach (var team in t.Team)
{
<li>team.TeamName</li>
}
</ul>
</li>
}
Please help me to understand how can i output data from two or more tables in my view

If tables are connected to each other through foreign key like in your case then you can use other table as property. Like TeamType.Teams. But I see that you are not referencing the TeamType in your Team class.
Edit your class like:
public class Team
{
[Key]
public int TeamId { get; set; }
public int TypeId { get; set; }
public string TeamName { get; set; }
public virtual TeamType Type{get;set;} // Add this to your class
}
Then use Team.Type to access Type table as property. Like:
#foreach (var team in t.Team)
{
<li>team.Type.TypeName</li>
}
But if the tables are not connected to each other then simplest answer is you have to create ViewModel for that. Now what is a ViewModel, that is not so simple, To study about ViewModel follow the link :
http://www.codeproject.com/Articles/687061/Using-Multiple-Models-in-a-View-in-ASP-NET-MVC-4
Here is another more simpler link:
http://sampathloku.blogspot.ae/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html

Related

repeater foreach in asp.net mvc

I'm building a website in ASP.Net, using MVC, and need to list a set of results
but i get error in the code
model:
public class Customers
{
public int Id { get; set; }
public string Name { get; set; }
public List<Customers> Itemlst { get; set; }
}
controller:
public ActionResult List()
{
Customers itemobj = new Customers();
return View(itemobj);
}
view:
#foreach(var item in Model.Itemlst)
{
<tr>
<td>Items ID:</td>
<td>#item.ID</td>
<td>Items Name:</td>
<td>#item.Name</td>
</tr>
}
</table>
From the NullReferenceException that you are receiving we can see that the issue is because of the Itemlst not being initialised. One of the ways to solve this is just to make sure that there is a valid list when you create the object:
public class Customers
{
public Customers()
{
Itemlst = new List<Customers>();
}
public int Id { get; set; }
public string Name { get; set; }
public List<Customers> Itemlst { get; set; }
}
So you can add values to the list in your action if need:
public ActionResult List()
{
Customers itemobj = new Customers();
var example = new Customers ();
example.Id = 1;
example.Name = "Example";
itemobj.Add();
return View(itemobj);
}
I don't know if you are just using this as an example for your question, but I can't help but notice that there is something weird. You could use something different like:
public class ViewModel // Name to what makes sense to you
{
// Some other properties...
public List<Customer> Customers { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
Or you could just use List<Customer> as your model in the view directly (yes, your model can be a object which is simply a list of objects).
When you pass the Customers list to the view, this list itself is the model.
Change Model.Itemlst —> Model inside the foreach loop.
This will iterate the list of customers.

How to use #html.hiddenfor() two view in MVC - one for getting data from database and other to store data

fist model get the list of questions.
but i am not able to access them while using #Html.HiddenFor() etc
these item are visible if i use #Html.Hidden() or anything without ....For method...
any idea how can i do this
here are my classes
public class QuestionModel
{
public int Id { get; set; }
public string QuestDes { get; set; }
public int Aspect { get; set; }
}
public class AnswerModel
{
public int Id { get; set; }
public string SelectedAns { get; set; }
public virtual QuestionModel Question { get; set; }
public virtual PersonModel Person { get; set; }
}
my controller code
public ActionResult GPage2()
{
var tview = new Tuple<List<QuestionModel>,AnswerModel>(getQuestions(),new AnswerModel());
return View(tview);
}
private List<QuestionModel> getQuestions()
{
var qList = (from q in dbcon.Questions
orderby q.Id
select q).ToList();
return qList;
}
in cshtml page
#model Tuple<List<QuestionModel>,AnswerModel>
<td> #Html.Label(Model.Item2.SelectedAns)</td>
#Html.LabelFor(.......................) not working
from what you have posted you need to use a view model that includes your 2 models
public class ViewModel{
public List<QuestionModel> Questions { get; set; }
public List<AnswerModel> Answers { get; set; }
}
then on your view
#model ViewModel
using this setup your for helpers should work. since it is a list putting them in a foreach would look something like this.
#foreach(var temp in Model.Questions){
#Html.LabelFor(x => temp.Aspect)
//etc
}

Model count = null

I'm rewriting this question:
I have 2 models. Entry and Topic.
public class Entry
{
public int EntryId { get; set; }
public int UserId { get; set; }
public int TopicId { get; set; }
public String EntryQuestion { get; set; }
public String EntryAnswer { get; set; }
public int EntryReview { get; set; }
public String QuestionValidationURL { get; set; }
public virtual ICollection<Topic> TopicList { get; set; }
}
public class Topic
{
public int TopicId { get; set; }
public String TopicName { get; set; }
}
I followed an example on ASP.Net/MVC to set up my models this way.
What I would like to do is for every entry item I have a TopicId, but then I'd like to convert that to a TopicName by accessing my TopicList.
My question is, how do I load TopicList?
In the examples I'm following I'm seeing something about LazyLoading and EagerLoading, but it doesn't seem to be working.
I tried doing the following from my Entry controller:
db.Entries.Include(x => x.TopicList).Load();
But that still gives me a TopicList of 0 (which is better than null)
How can I do this?
In my view I'm binding to the Entries like this:
#model IEnumerable<projectInterview.Models.Entry>
I would like to access the TopicList here:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.TopicId)
</td>
...
</tr>
I'd like to use the TopicId in this loop and display the TopicName that is part of the object in the collection.
I'm assuming you're following an Entity Framework example. You're trying to create a one-to-many relationship, as far as I can tell, although I'm unsure about which end is which.
In the general case, to establish a one-to-many relationship, you have to do something like this:
public class One
{
[Key]
public int Id { get; set; }
public virtual ICollection<Many> Many { get; set; }
}
public class Many
{
[Key]
public int Id { get; set; }
[ForeignKey("One")]
public int OneId { get; set; }
public virtual One One { get; set; }
}
If what you're trying to do is have one Entry relating to many Topic objects, then you're almost there but you're lacking something.
For the ICollection<Topic> to actually contain anything, the (many) Topic objects need to have a foreign key to the (one) Entry. (It also doesn't hurt to explicitly mark the primary key on both sides, rather than relying on the EF conventions.)
public class Topic
{
[Key]
public int TopicId { get; set; }
public String TopicName { get; set; }
[ForeignKey("Entry")]
public int EntryId { get; set; }
public virtual Entry Entry { get; set; }
}
public class Entry
{
[Key]
public int EntryId { get; set; }
public int UserId { get; set; }
public int TopicId { get; set; }
public String EntryQuestion { get; set; }
public String EntryAnswer { get; set; }
public int EntryReview { get; set; }
public String QuestionValidationURL { get; set; }
public virtual ICollection<Topic> TopicList { get; set; }
}
Now TopicList should be an actual and populated collection, without the need to do an Include.
If, on the other hand, you want one Topic relating to many Entry objects, then you have it a little backwards. The correct way would be:
public class Topic
{
[Key]
public int TopicId { get; set; }
public String TopicName { get; set; }
public virtual ICollection <Entry> Entries { get; set; }
}
public class Entry
{
[Key]
public int EntryId { get; set; }
public int UserId { get; set; }
public String EntryQuestion { get; set; }
public String EntryAnswer { get; set; }
public int EntryReview { get; set; }
public String QuestionValidationURL { get; set; }
[ForeignKey("Topic")]
public int TopicId { get; set; }
public virtual Topic Topic { get; set; }
}
In this case, you may or may not use db.Entries.Include(x => x.Topic) depending on whether you want them loaded all at once or one-by-one on demand. Regardless of what you choose, the following expression should return the proper value:
myEntry.Topic.TopicName
If I understand you correctly you have added the list of Topics to the Entry just to get the name of the topic when displaying the entry. The best way to do this is to actually have a Topic property in your entry model. So your model would look like this:
public class Entry
{
public int EntryId { get; set; }
public int UserId { get; set; }
public int TopicId { get; set; }
public String EntryQuestion { get; set; }
public String EntryAnswer { get; set; }
public int EntryReview { get; set; }
public String QuestionValidationURL { get; set; }
//Change this.....
public virtual Topic Topic { get; set; }
}
Then in your view you would use (assuming the Model is an IEnumerable):
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => modelItem.Topic.TopicName )
</td>
...
</tr>
This link has a great example of how to do this:
http://weblogs.asp.net/manavi/archive/2011/03/28/associations-in-ef-4-1-code-first-part-2-complex-types.aspx
In my opinion problem is with casting. In view you have IEnumerable<projectInterview.Models.Entry> while Topics is ICollection<Topic>, which is a collection of different type
Topics = null means there are no Topics in the list to iterate over. How do you fill them? Your view expects IEnumerable how do you cast your topics to the entries?
Based on the original question I've added a small working example, maybe it helps you to find your bug.
Controller:
public class TestController : Controller
{
public ActionResult Index()
{
var viewModel = new ViewModel()
{
Topics = new List<Topic>()
};
viewModel.Topics.Add(new Topic() { header = "test" });
viewModel.Topics.Add(new Topic() { header = "test2" });
return View(viewModel);
}
}
Model:
public class ViewModel
{
public virtual ICollection<Topic> Topics { get; set; }
public int getCount()
{
return Topics.Count;
}
}
public class Topic
{
public string header { get; set; }
}
View:
#model testProject.Models.ViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Model.getCount()
#foreach(var item in Model.Topics)
{
<div>#item.header</div>
}
Output:
Index
2
test
test2
It seems that you are not initializing your Topics anywhere in the code. If the collection is null it means it is not initialized. If you instantiate it with
ICollection<Topic> Topics = new List<Topic>();
Once initialized you should receive zero when calling Topics.Count. If you do not make a call to a database it will stay zero.
In your case check whether you are instantiating the Topics.

MVC 4: building composite viewmodel

I am new to ASP.NET MVC. I need to build a composite viewmodel out of three nested or cascading classes: Sport>Tournament>TournamentEvent
public class Sport
{
public int Id { get; set; }
public string SportName { get; set; }
public virtual ICollection<Tournament> Tournaments { get; set; }
}
public class Tournament
{
public int Id { get; set; }
public string TournamentName { get; set; }
public int SportId { get; set; }
public virtual ICollection<TournamentEvent> TournamentEvents { get; set; }
}
public class TournamentEvent
{
public int Id { get; set; }
public string EventName { get; set; }
public int TournamentId { get; set; }
}
As you can gather, each sport contains a collection of tournaments and each tournament contains a collection of events. I need to construct an unordered list, like so:
<li> Soccer
<li>English Premier League
<li>Chelsea v Arsenal</li>
</li>
</li>
I need to build a composite viewmodel, using linq, to pass to my view, but I just can't figure it out. Please help
Don't you just need a parent vie model that contains a list of Sport?
public class Sport
{
public List<Sport> Sports { get; set; }
}
You can iterate through the collections using razor.
Can you clarify where you think linq comes into it? I might have got the wrong end of the stick.
I don't think that works, tom. I need access to the Tournament and TournamentEvent classes and I need to load them into my object, which is where linq comes in. In the SportsController:
public partial class SportsController : Controller
{
private MyDb db = new MyDb();
public virtual ActionResult Index()
{
var menuObject = from s in db.Sports
select s;
return View(menuObject);
}
}
Create a class call it SportTournamentEventViewModel.cs
using "LibraryName".Models;
public class SportTournamentEventViewModel
{
public List<Sport> Sports {get;set;}
public List<Tournament> Tournaments {get;set;}
public List<TournamentEvent> Events {get;set;}
}
in your action
private NameOfEntities db = new NameOfEntities();
public ActionResult "ActionResultName"()
{
db.Configuration.LazyLoading = false;
var sportList = db.Sport.ToList();
var tournamentList = db.Tournament.ToList();
var eventList = db.TournamentEvents.ToList();
var viewModel = new SportTournamentViewModel
{
Sports = sportList,
Tournaments = tournamentList,
Events = eventList,
};
return View(viewModel);
}

Help with displaying master detail data into mvc3 view

I have the following models:
public class Page
{
public int PageID { get; set; }
public string Name { get; set; }
public string Content { get; set; }
public DateTime? DateCreated { get; set; }
public bool IsPublished { get; set; }
public string ModifiedBy { get; set; }
public DateTime? DateModified { get; set; }
public int UserID { get; set; }
public int CategoryID { get; set; }
public virtual User User { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
[Required(ErrorMessage = "Category name is required.")]
[Display(Name = "Category Name")]
public string Name { get; set; }
public virtual ICollection<Page> Pages { get; set; }
}
and I want to populate this navigation list:
<div id="centeredmenu" class="nav-border nav-color">
<ul>
#foreach (var pages in Model)
{
<li>CATEGORY NAME GOES HERE
<ul>
#foreach (var pages in Model)
{
<li>PAGE NAMES GO HERE</li>
}
</ul>
</li>
}
</ul>
</div>
but I'm having problems implementing the controller. I tried this ViewModel:
public class MainPageModels
{
public Category Categories { get; set; }
public Page Pages { get; set; }
}
but it just confused me even more with this error message:
System.Data.Edm.EdmEntityType: : EntityType 'MainPageModels' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet �MainModels� is based on type �MainPageModels� that has no keys defined.
This is my controller:
public ActionResult Index()
{
var pages = db.MainModels.Select(p => p.Pages).Select(c => c.Category);
return View(pages);
}
I may be missing something simple here.
Posting this here for the code/syntax
public class Person
{
[Key]
public int PersonID { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public class DataContext : DbContext
{
EntitySet<Person> Persons { get; set; }
}
Your View Model can then do the following
public class PersonAddViewModel
{
public string Name { get; set; }
public string LastName { get; set; }
public void CreateViewModelFromDataModel(Person person)
{
this.Name = person.Name;
this.LastName = person.LastName ;
}
}
This is just an example, just to show the difference between a Data Model and a View Model
Your View would then be a strongly typed view of PersonAddViewModel
Here my solution to my parent-child list problem:
I created a ViewModel to house both my categories and pages:
public class HomeViewModels
{
[Key]
public int HomeViewKey { get; set; } //This is a MUST!
public IEnumerable<Category> ViewCategories { get; set; }
public IEnumerable<Page> ViewPages { get; set; }
public void CreateHomeViewModel(IEnumerable<Category> categories,
IEnumerable<Page> pages)
{
this.ViewCategories = categories;
this.ViewPages = pages;
}
}
Then edited my controller to populate the viewmodel:
public ActionResult Index()
{
HomeViewModels homePages = new HomeViewModels();
homePages.CreateHomeViewModel(db.Categories.ToList(),
db.Pages.ToList());
return View(homePages);
}
and finally creating the ul-li lists with the following:
#{var hvCategories = Model.ViewCategories;}
#foreach (var categories in hvCategories)
{
<li>#Html.ActionLink(categories.Name, "Index", "Home")
<ul>
#{var hvPages = Model.ViewPages
.Where(p => p.CategoryID == categories.CategoryID);}
#foreach (var pages in hvPages)
{
<li>#Html.ActionLink(pages.Name, "Index", "Home")</li>
}
</ul>
</li>
I hope this helps anyone who plans to build a nested list using a parent-child model. This took me two days to figure out. Cheers!

Resources