repeater foreach in asp.net mvc - 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.

Related

How to insert and display User and Address model using Entity Framework

I want to display both user info and address model in the same view.
These are my code structures:
In Data Access Layer, I have model classes:
User.cs:
public class User
{
[Key]
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string RestaurantName { get; set; }
public string PrimaryPhone { get; set; }
}
Location.cs:
public class Location
{
public int Id { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
public User User { get; set; }
}
So, I have two separate repositories for user and address models which perform add and get all functions which is working perfectly fine.
Now, I want both of this model information should be displayed in the view at the same time.
How can I combine both in the same view. I'm unable to do it. I can do it, but the thing is both are displayed in separate views.
Any advice would be appreciated!
Use a ViewModel. Your ViewModel could look something like this:
public class MyViewModel
{
public User UserVm {get;set;}
public Location LocationVm {get;set;}
}
Use the MyViewModel in your view. Your controller will accept a MyViewModel object.
You can then pass the LocationVm and UserVm objects from your viewModel to your repository.
Add One more Property To your User Model like below
-- Model Section
public class User
{
public List<Location> location {get;set;}
}
-- Controller Section
public ActionResult Index()
{
List<Location> loc= new List<Location>() { new Location{ City = "one" }, new
Location{ City = "two" } };
List<User> user= new List<User>() { new User{ FirstName = "A", location =
loc }, new User{ FirstName = "B" } };
return View(user);
}
-- View Section
#model IEnumerable<YourSolutionName.Models.User>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
#{
if (item.location != null) {
foreach(var i in item.location)
{
<h1>#i.City</h1>
}
}
}
}
This is one approach by using, we can use two different models on same view.
As for demo i added static values you can add dynamic using your context object.
it may help you. Thank You

MVC View Page not showing Value

My Model class is below:
I have three classes two of them are partial class and one is simple class.......
[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration
{
}
public class RegistrationMetaData
{
public string Id { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public virtual ICollection<Images> Images { get; set; }
}
[MetadataType(typeof(ImagesMetaData))]
public partial class Images
{
}
public class ImagesMetaData
{
public string id { get; set; }
public string stuid { get; set; }
public string stuimg1 { get; set; }
public virtual ICollection<Registration> Registrations { get; set; }
}
public class EmployeeViewModel
{
public string Name { get; set; }
public string stuimg1 { get; set; }
}
public class NotificationViewModel
{
public Registration registration { get; set; }
public Notification notification { get; set; }
public IEnumerable<EmployeeViewModel> EmployeeViewModel { get; set; }
public Images images { get; set; }
}
Then I have used the below code in controller class to fetch Images record with foreign key in registration table.
IEnumerable<EmployeeViewModel> model1 = null;
model1 = (from e in db.Registrations
join j in db.Images on e.Id equals j.stuid
where e.Email == Email
select new EmployeeViewModel
{
Name = e.Name,
stuimg1 = j.stuimg1
}).ToList();
var mixmodel = new NotificationViewModel
{
EmployeeViewModel = model1
};
return View(mixmodel);
Atlast my view page is like this:-
#model IEnumerable<Amar.Models.NotificationViewModel>
#foreach (var item in Model)
{
#item.EmployeeViewModel.stuimg1
}
But I am getting an error
System.Collections.Generic.IEnumerable' does not contain a definition for 'stuimg1' and no extension method 'stuimg1' accepting a first argument of type 'System.Collections.Generic.IEnumerable' could be found (are you missing a using directive or an assembly reference?)
I have gone through debugging my code is fine till controller page...but from view page the values are not showing.I think there is some little mistake i have made...
Please someone help me..I am trying to solve this problem since 2 weeks....
I want to fetch data from one more class on the same view page thats why I am using NotificationViewModel class.
return View(mixmodel);
Your view is expecting a type of IEnumerable<NotificationViewModel> but mixmodel is just a NotificationViewModel
I'm not seeing what you are achieving by having this additional class 'NotificationViewModel'. If your view were to be changed to expect an IEnumerable<EmployeeViewModal> you could pass in model1 directly.
You could then change your view to:
#foreach (var item in Model)
{
#item.stuimg1
}
If you do indeed need this extra layer of abstraction for some other part of your view then you need to sit and think about what is a a single instance and what is a list. Try drawing it if you're having trouble.

ASP.ET MVC 4 to view data from several tables ViewBag

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

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
}

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);
}

Resources