I have created two different tables with entity.
The code looks like this:
public class Frisorer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Scheman> Schema { get; set; }
}
public class Scheman
{
public int Id { get; set; }
public DateTime Schemat { get; set; }
public virtual Frisorer frisorer { get; set; }
}
My context file:
public class Context : DbContext
{
public Context()
: base("DefaultConnection")
{
}
public DbSet<Frisorer> Frisorer { get; set; }
public DbSet<Scheman> Scheman { get; set; }
}
The tables get created allright with keys establishing a relationship between them.
What i would like now is to be able to display both the names/id of my frisor and their schemas in the same view in MVC. But when i try to add a view, I can only choose strongly typed views with either Frisorer OR Schemas...How can I do to display both my tables together?
EDIT:
I created a new class where I encaosulated the two other classes:
public class Frisorer
{
public int Id { get; set; }
public string Name { get; set; }
public List<Scheman> Schema { get; set; }
}
public class Scheman
{
public int Id { get; set; }
public DateTime Schemat { get; set; }
public virtual Frisorer frisorer { get; set; }
}
public class BigViewModel
{
public List<Frisorer> Frisorer { get; set; }
public List<Scheman> Scheman { get; set; }
}
And the controll:
public ActionResult hopp()
{
BigViewModel bv = new BigViewModel();
bv.Frisorer = (from o in cont.Frisorer select o).ToList();
bv.Scheman = (from or in cont.Scheman select or).ToList();
return View(bv);
}
I create a view where I choose BigViewModel as the strongly typed and list as scaffolding.
Get this error:
The model item passed into the dictionary is of type 'MvcApplication3.Models.BigViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MvcApplication3.Models.BigViewModel]'
You are getting the exception because you are passing an single object to the view when the view is expecting a collection of BigViewModel.
Try changeing the modelbinding in your view to: #model BigViewModel instead of #model IEnumerable<BigViewModel> and then iterate the collections in your Model:
#foreach(var frisor in Model.Frisorer)
{
//do stuff
}
#foreach(var schema in Model.Scheman)
{
//do stuff
}
Create a third class, some kind of a ViewModel/Wrapper, that will encapsulate everything you need. Reference it then in your View.
You just need to change the model in the view from #model IEnumerable<BigViewModel> to #model BigViewModel and then iterate over Frisorer and Scheman, something like so:
#model BigViewModel
<ul>
#foreach(var item in Model.Frisorer)
{
<li>#item.Id - #item.Name</li>
}
</ul>
<ul>
#foreach(var item in Model.Scheman)
{
<li>#item.Id - #item.Schemat</li>
}
</ul>
Related
New to MVC and wanting to pass two models to the view. The idea being one is a list of data, the other is simply a datetime to show when it was last uploaded in bulk.
My models are:
public class DataModel
{
public int IDX { get; set; }
public string PyR { get; set; }
public string CN { get; set; }
public string A { get; set; }
public string B_R { get; set; }
public DateTime L_I { get; set; }
}
public class DataUpdated
{
public DateTime LastImport { get; set; }
}
And my view model is:
public class DataViewModel
{
public IEnumerable<Model.DataModel> Data { get; set; }
public Model.DataUpdated LastUploadDate { get; set; }
}
I am sending the view model to the view in the controller with:
ViewModels.DataViewModel vm = new ViewModels.DataViewModel();
vm.Data = C_List;
vm.LastUploadDate = du;
return View(vm);
I have then tried to reference this in my view, with:
#model CCA_Data.ViewModels.DataViewModel
But when I try and access the Data model from the view model in the following line of code in my view:
#foreach (var Data in Model.Data)
I get the error:
IENumerable < DataViewModel > does not contain a definition for
Data
2 questions:
What am I doing wrong?
Why does it think DataViewModel is IENumerable?
Just answering here so that others don't have to go through all of the comments...
Don't forget to Rebuild the project so that it can figure out all the namespaces and references.
I've two tables as Models in my project Like:-
public partial class TblAlbum
{
public int ID { get; set; }
public string Album { get; set; }
public string Artists { get; set; }
public Nullable<int> AudioID { get; set; }
public Nullable<int> VideoID { get; set; }
public virtual TblVideo TblVideo { get; set; }
public virtual TblAudio TblAudio { get; set; }
}
and
public partial class TblAudio
{
public int ID { get; set; }
public string Name { get; set; }
public string Alt { get; set; }
public string Artist { get; set; }
public string Image { get; set; }
public int LangID { get; set; }
public virtual TblLanguage TblLanguage { get; set; }
public virtual ICollection<TblAlbum> TblAlbums { get; set; }
}
Now I've Made a ViewModel as GetDetailsVM that have access to both tables and has the LINQ Query as:-
public class GetDetailsVM
{
private MusicEntities db = new MusicEntities();
public IEnumerable<dynamic> GetAudio()
{
var AudioList = from au in db.TblAudios
join al in db.TblAlbums on au.ID equals al.AudioID into ar
from al in ar.DefaultIfEmpty()
select new { au,al };
return AudioList.ToList();
}
}
My ViewModel(AudioAlbumVM) to read Getaudio() should be something like this:-
public class AudioAlbumVM
{
public IEnumerable<dynamic> AudioObjList { get; set; }
public string AlbumName { get; set; }
}
Now I want to access this ViewModel in my controller and then use it in my cshtml.
My Controller:-
public ActionResult Audio()
{
ViewBag.Title = "Audio";
var AudioSummary = new GetDetailsVM();
var viewModel = new AudioAlbumVM
{
AudioObjList = AudioSummary.GetAudio().First()
};
return View(viewModel);
}
UPDATE
My View(Audio.cshtml) is as follows:-
#model GarhwalMusic.Models.AudioAlbumVM.AudioObjList
<a class="art" href="single.html"> #Model.AudioObjList</a>
I was going through this question LINQ left join only works in the ActionResult but I'm completely lost . Need help and explanation on how to create AudioAlbumVM using another ViewModel(GetDetailsVM) then in controller and then in cshtml. Any help is greatly appreciated!!
Taking this from your comments
Now I'm getting this error:- The model item passed into the dictionary is of type 'GarhwalMusic.Models.AudioAlbumVM', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[GarhwalMusic.Models.AudioAlbumVM]'.
Problem is with this code
var viewModel = new AudioAlbumVM //its a single model
{
AudioObjList = AudioSummary.GetAudio().First()
};
But it seems like your view is expecting a model of type IEnumerable<GarhwalMusic.Models.AudioAlbumVM> or (List<GarhwalMusic.Models.AudioAlbumVM>). You need to either pass a List<GarhwalMusic.Models.AudioAlbumVM> to your view or change your view to accept a model of type GarhwalMusic.Models.AudioAlbumVM.
But looking at your code I assume that you are trying to pass the collection of AudioObjList into your View. So your view must accept a model of type
GarhwalMusic.Models.AudioAlbumVM.AudioObjList and you need to just Pass in only the viewModel.AudioObjList from your controller.
EDIT 1: After you added more details of your view, You are making a mistake in the way you are accessing the data.
your Model.AudioObjList is of type IEnumerable<dynamic> and how can you just print something on the Vie like #Model.AudioObjList ?? I am referring to this code
<a class="art" href="single.html"> #Model.AudioObjList</a>
You need to typecast this dynamic type into what ever object you have created in your linq and then extract its property value. Something like
#((yourObject)Model.AudioObjList[0]).propertyName
(yourObject)Model.AudioObjList[0] type casts your dynamic data into a type yourObject.
you need [0] because your AudioObjList is of type IEnumerable<dynamic>. So taking the first data.
I have a model which is storing mycustomer new request information.
In another history model i am storing all previous request of the customer.
In view i would like to take new order and also see his previous orders and suggest some food after seeing his previous order.
Here are my models...
public class CustomerFoodModel
{
public DateTime FoodRequestCreated { get; set; }
public string FoodRequestType { get; set; }
...
...
}
public class CustomerHistoryModel
{
public string Name { get; set; }
public DateTime FoodRequestCreated { get; set; }
public string FoodRequestType { get; set; }
...
...
}
Helper.cs file
public static CustomerFoodModel getCustomerDetails(int id) // id is loyalty card number
{
// get details from (cutomer) sql table
//store it in (CustomerFoodModel)
// check if it has previous orders
getCustomerHistoryDetails(id);
....
}
public static CustomerHistoryModel getCustomerHistoryDetails(int id)
{
// get deails from (history) sql table
// store it in (CustomerHistoryModel
}
In my controller, I am passing my (CustomerFoodModel) to the view.
public ActionResult EditCustomerRequest(int id, string name, string date)
{
CustomerFoodModel CRequest = Helper.getCustomerDetails(id);
...
return PartialView("EditCustomerRequest",CRequest);
}
How do I show the (CustomerHistoryModel) in the same view.? Is there possible to include (CustomerHistoryModel) in (CustomerFoodModel)?
Create a new class to wrap both of the model.
public class CustomerFoodModel
{
public CustomerFoodModel CustomerFood { get; set; }
public CustomerHistoryModel CustomerHistory { get; set; }
}
And on your controller
public ActionResult EditCustomerRequest(int id, string name, string date)
{
CustomerFoodModel CRequest = Helper.getCustomerDetails(id);
CustomerHistoryModel CHModel = Helper. getCustomerHistoryDetails(id);
return PartialView("EditCustomerRequest",new CustomerFoodModel(){
CustomerFood = CRequest,
CustomerHistory = CHModel
});
}
I think the best approach is to use a partial view inside the main view. The partial view can call back to another controller to get a new model and pass that model to the partial view. This keeps things better seperated.
Look at this post for a similar issue.
Using partial views in ASP.net MVC 4
Use wrapper class which contain both of class
public class CustomerViewModel
{
public CustomerFoodModel FoodModel { get; set; }
public CustomerHistoryModel HistoryModel { get; set; }
}
You have a few options. I would probably could create a view model that contains both of your models:
public class CustomerViewModel
{
public CustomerFoodModel FoodModel { get; set; }
public CustomerHistoryModel HistoryModel { get; set; }
}
Or, depending on your data structure, you may have multiple history entries per customer:
public class CustomerViewModel
{
public CustomerFoodModel FoodModel { get; set; }
public List<CustomerHistoryModel> HistoryModels { get; set; }
}
Then your getCustomerDetails function would return a CustomerViewModel instead.
How can I fetch and insert data at a specific time in one view in mvc razor view? I mean to fill a dropdown list from the database in create view.
I want to fill the following when I add the subject and cheater models.
department list
semester list
standard list
stream list
cheater model:
namespace firstapp.Models
{
public class chepter
{
[ForeignKey("dip_id")]
public int dipart_id { get; set; }
public int chep_id { get; set; }
public string subject { get; set; }
public string chepter { get; set; }
public List<dipartment> dipartlist { get; set; }
public List<dipartment> stdlist { get; set; }
public List<dipartment> semlist { get; set; }
public List<dipartment> stremlist { get; set; }
}
}
department model:
namespace firstapp.Models
{
public class dipartment
{
public int dip_id { get; set; }
public string dipart { get; set; }
public string std { get; set; }
public string sem { get; set; }
public string strem { get; set; }
}
}
#Html.DropDownListFor(model => model.dipart_id, new SelectList(Model.dipartlist.Select(s => new SelectListItem() { Value = s.dip_id, Selected = false, Text = s.dipart })), "Select")
Change your model so the list property is a selectlist:
public SelectList<dipartment> dipartlist { get; set; }
Then, when you populate the model call a service class method(you might not have a service layer, I just prefer to not have database calls in the controller)
dipartlist = _departmentService.GetAsSelectList();
The GetAsSelectList service method looks like this:
public SelectList GetAsSelectList()
{
return (from d in _context.Set<department>().OrderBy(x => x.dipart)
select new
{
Id = d.dipart_id,
Name = d.dipart
}).ToList();
}
And finally your view:
#Html.DropDownListFor(model => model.dipart_id, Model.dipartlist)
This technique means you don't have linq in either the view or controller. Also as you're only creating the selectlist in one place (the service), you can cache it with MemoryCache to prevent multiple requests for the same data. And as it looks like you're populating 4 selectlists, this might be useful.
My task is to show multiple models into a single view.I've created a ViewModel for my requirement but I'm not meeting my requirement.
please have a look into the below code and rectify me where m i going wrong ???
public partial class StudentsDetail
{
public int StudentID { get; set; }
public int ParentID { get; set; }
public string StudentName { get; set; }
public string Gender { get; set; }
public string FatherName { get; set; }
public string MotherName { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
public virtual ParentsDetail ParentsDetail { get; set; }
public virtual SchoolDetail SchoolDetail { get; set; }
}
//Model 2
public partial class ParentsDetail
{
public ParentsDetail()
{
this.StudentsDetails = new HashSet<StudentsDetail>();
}
public int ParentID { get; set; }
public string Occupation { get; set; }
public string Organization { get; set; }
public string AnnualIncome { get; set; }
public virtual ICollection<StudentsDetail> StudentsDetails { get; set; }
}
//ViewModel Which I have created
public class ParentsInformationViewModel
{
public List<StudentsDetail> StudentsDetails { get; set; }
public List<ParentsDetail> ParentsDetails { get; set; }
public ParentsInformationViewModel(List<StudentsDetail> _studentDetails, List<ParentsDetail> _parentsDetails) //Should i pass all the required parameters that i want to display in view ????
{
StudentsDetails = _studentDetails;
ParentsDetails = _parentsDetails;
}
//And finally this is my method defined in the StudentController (Have i defined it in a right place/way??)
public ActionResult StudentViewModel()
{
ViewBag.ParentsDetail = new ParentsDetail(); //ParentsDetail is my controller
List<StudentsDetail> studentListObj = StudentsDetailsDAL.GetStudentDetails();
List<ParentsInformationViewModel> ParentInfoVMObj = new List<ParentsInformationViewModel>();
//foreach (var student in studentListObj)
//{
// ParentInfoVMObj.Add(new ParentsInformationViewModel(student.StudentID, student.ParentID));
//}
//ParentInfoVMObj.Add(ParentInfoVMObj); /// don't know how to call the required viewmodel
return View(ParentInfoVMObj);
}
I know that the above method of a ViewModel is wrong but how to use it or where am i going wrong I can't get.
I want to display the ViewModel in the view as a detailed view .
Please, correct me as I'm a starter in MVC3 .
Thanks In Advance!!
In your controller, define your action method as follows.
public ActionResult ParentsDetails()
{
var studentDetails = new List<StudentDetail>();
var parentDetails = new List<ParentsDetail>();
// Fill your lists here, and pass them to viewmodel constructor.
var viewModel = new ParentsInformationViewModel(studentDetails, parentDetails)
// Return your viewmodel to corresponding view.
return View(viewModel);
}
In your view define your model.
#model MySolution.ViewModels.ParentsInformationViewModel
Is there in your view declared that you are receiving model of type
In view:
#model IEnumerable<ParentsInformationViewModel>