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.
Related
Need help in creating LINQ query to group and filter with related entities.
Here is my model classes.
public class Application
{
[DisplayName("Application")]
public int ApplicationId { get; set; }
[DisplayName("Application")]
public string Name { get; set; }
public List<DashboardEntry> DashboardEntries { get; set; }
}
public class Cluster
{
[DisplayName("Cluster")]
public int ClusterId { get; set; }
[DisplayName("Cluster")]
public string Name { get; set; }
}
[Bind(Exclude = "AlbumId")]
public class DashboardEntry
{
[ScaffoldColumn(false)]
public int DashboardEntryId { get; set; }
public int ClusterId { get; set; }
public int ApplicationId { get; set; }
public HealthStatusIndicator Status { get; set; }
public string Incident { get; set; }
public string Remarks { get; set; }
public virtual Cluster Cluster { get; set; }
public virtual Application Application { get; set; }
}
Index action method is as follows
public ActionResult Index()
{
//var dashboardEntries = db.DashboardEntries.Include(d => d.Application).Include(d => d.Cluster);
var dashboardEntries = db.DashboardEntries
.Include(d => d.Application)
.Include(d => d.Cluster)
.GroupBy(d => d.Application);
return View(dashboardEntries.ToList());
}
In the view, model declaration is as below.
#model IEnumerable<HealthCheckIndex.Models.DashboardEntry>
I'm getting an error
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery1[System.Linq.IGrouping2[HealthCheckIndex.Models.Application,HealthCheckIndex.Models.DashboardEntry]]',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[HealthCheckIndex.Models.DashboardEntry]'.
If I change the model declaration in view as below, I'm getting a another error that Cluster is not accessible.
#model IEnumerable>
I want to group the dashboard entries into different applications and filter the groups by choosing the max dashboard entry from each group.
The type that you are passing currently to the view does not match the specified type
#model IEnumerable<HealthCheckIndex.Models.DashboardEntry>
Currently you are passing something like a dictionary where the key is Application and the value is a IEnumerable of HealthCheckIndex.Models.DashboardEntry
In order to make it you have one of 2 options:
Replace the last line of the controller action with
return View(dashboardEntries.SelectMany(c=> c).ToList());
Change model definition in the view to match the list your returning
Hi Im a new to MVC3 and i am having problem in returning two variables here is my controller code
public ActionResult Create()
{
using (var context = new material_managementEntities())
{
var blogs = (from cs in context.GROUP_MASTER
where cs.GROUP_NAME == "MIC"
select cs.ID).FirstOrDefault();
var droplist = new TRANSACTION();
droplist.GROUP_MASTER_ID = blogs;
droplist.GROUP_NAME = "MIC";
var directory_master = db.DIRECTORY_MASTER.Include(d => d.CATEGORY_MASTER).Include(d => d.REPRESENTATIVE_MASTER);
droplist.dir_data = directory_master.ToList();
return View(droplist);
}
}
here Transaction is one table and DIRECTORY_MASTER is another and GROUP_MASTER_ID is a foreign key to Transaction table, what i want is the toList data will be displayed in a modalpopup box so i need to pass data available from both tables
here is model
namespace Material.Models
{
using System;
using System.Collections.Generic;
using System.Web.Mvc;
public partial class TRANSACTION
{
public int ID { get; set; }
public int GROUP_MASTER_ID { get; set; }
public string GROUP_NAME { get; set; }
public string dir_data { get; set; }
public string NAME { get; set; }
public string ADDRESS_DETAILS { get; set; }
public string CONTACT_PERSON { get; set; }
public Nullable<int> TEL_NO { get; set; }
public Nullable<int> CELL { get; set; }
public Nullable<int> FAX { get; set; }
public string EMAIL_ID { get; set; }
public Nullable<int> OPENING_BALANCE { get; set; }
public Nullable<System.DateTime> OPENING_BALANCE_DATE { get; set; }
public string VERIFIED { get; set; }
public virtual GROUP_MASTER GROUP_MASTER { get; set; }
}
}
Either you can use a
viewbag.directory_master = (db.DIRECTORY_MASTER.Include(d => d.CATEGORY_MASTER).Include(d => d.REPRESENTATIVE_MASTER)).ToList();
and then iterate your viewbag.directory_master from your model and display the required ones.
or you can create a custom view model containing directory_master and TRANSACTION like
public class DashboardModel
{
public TRANSACTION transation{get;set;}
public List<directory_master>directoryMaster{get;set;}
}
so your action will be like this
public ActionResult Create()
{
using (var context = new material_managementEntities())
{
var blogId = (from cs in context.GROUP_MASTER
where cs.GROUP_NAME == "MIC"
select cs.ID).FirstOrDefault();
DashboardModel dashboardModel= new DashboardModel();
dashboardModel.transation.GROUP_MASTER_ID = blogId;
dashboardModel.transation.GROUP_NAME = "MIC";
dashboardModel.directoryMaster = (db.DIRECTORY_MASTER.Include(d => d.CATEGORY_MASTER).Include(d => d.REPRESENTATIVE_MASTER)).ToList();
return View(dashboardModel);
}
}
I would recommend strongly typing your MVC view to take a model of the type you require, and pass that model to the view via an argument in the return function of your controller's action method.
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>
I feel a bit stupid.
I'm trying to get a hang of MVC 4, using boxing as a functional example.
I have WeightCategories in the database (Heavyweights, etc), and Boxers.
Seem simple. The relation is a boxer has a current weight category, but when I edit, I want it to be able to change it with a drop down.
I understand how to do it if it's a list I've made myself in the code, but I have problem understanding how to "load" the list from the WeightCategory table and show it in the view/model of the boxer.
So, here is my code for the WeightCategory item:
[Table("WeightCategories")]
public class WeightCategory
{
[Key]
public int WeightCategoryId { get; set; }
public WEIGHT_CATEGORIES WeightCategoryType { get; set; }
[Display(Name = "Weight Category Name")]
[Required]
[MinLength(5)]
public string Name { get; set; }
[Display(Name = "Weight Limit In Pounds")]
public int? WeightLimit { get; set; }
}
Here is the code for the boxer item
[Table("Boxers")]
public class Boxer
{
[Key]
public int BoxerId { get; set; }
public WeightCategory CurrentWeightCategory { get; set; }
[Required]
public string Name { get; set; }
public int Wins { get; set; }
public int Losses { get; set; }
public int Draws { get; set; }
public int Kayos { get; set; }
}
In the view, I'm really not sure how to tackle that, I'm pretty sure it's not automatic and I need to load the table somewhere in the controller maybe... I'm looking for best practice or something.
Something like that in the view at the end:
#Html.DropDownListFor(model => model.CurrentWeightCategory.WeightCategoryId,
new SelectList(Model.WeightCategories, "WeightCategoryId", "Name",
Model.WeightCategories.First().WeightCategoryId))
You could design a view model:
public class MyViewModel
{
public Boxer Boxer { get; set; }
public IEnumerable<SelectListItem> WeightCategories { get; set; }
}
and then have your controller action populate and pass this view model to the view:
public ActionResult Edit(int id)
{
var model = new MyViewModel();
using (var db = new SomeDataContext())
{
// Get the boxer you would like to edit from the database
model.Boxer = db.Boxers.Single(x => x.BoxerId == id);
// Here you are selecting all the available weight categroies
// from the database and projecting them to the IEnumerable<SelectListItem>
model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
{
Value = x.WeightCategoryId.ToString(),
Text = x.Name
})
}
return View(model);
}
and now your view becomes strongly typed to the view model:
#model MyViewModel
#Html.DropDownListFor(
x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
Model.WeightCategories
)
I have a method in my repository to retrieve All records for Items
public IQueryable<Item> GetAll()
{
//The following causes a circular reference if you attempt to serialize it via an API call.
IQueryable<Item> items = context.Items.Include(c => c.UserProfile).Include(c => c.UserProfile1).AsQueryable();
return items;
}
This causes issues with Kendo Grid and serialization because of how I am including the foreign tables User Profile twice to be able to get the full name of the user whom created and modified the Item record.
Instead of Include(c => c.UserProfile) is there a way to only include the UserProfile.FullName column?
Today I am handling this in my ViewModel and creating a new subclass (this example is for Locations, not Items):
public class LocationsListViewModel
{
public IEnumerable<LocationsGrid> Locations { get; set; }
public IEnumerable<Facility> Facilities { get; set; }
public IEnumerable<string> AreaOptions { get; set; }
public int LocationCount { get; set; }
public class LocationsGrid
{
public int Id { get; set; }
public string DisplayLocation { get; set; }
public string Area { get; set; }
public string Zone { get; set; }
public string Aisle { get; set; }
public string Bay { get; set; }
public string Level { get; set; }
public string Position { get; set; }
public string Barcode { get; set; }
}
}
and then having to populate that in my Tasks or App Services layer (sits between controller and repository) like this:
viewModel.Locations = from l in locations.ToList()
select new LocationsListViewModel.LocationsGrid
{
Id = l.Id,
DisplayLocation = l.DisplayLocation,
Area = l.Area,
Zone = l.Zone,
Aisle = l.Aisle,
Bay = l.Bay,
Level = l.Level,
Position = l.Position,
Barcode = l.BarcodeValue
};
This seems like a lot of extra code and maintenance for each entity going forward. I'm sure there is a more efficient way to do this.
I typically use a Data-Transfer Object (basically just a class that has the exact data you're looking for, then returning objects of that type from your data-access method.
public IQueryable<ItemSummary> GetAll()
{
IQueryable<ItemSummary> items = context.Items
.Select(c => new ItemSummary {
FirstProfileName = c.UserProfile.FullName,
SecondProfileName = c.UserProfile1.FullName,
ScalarProp1 = c.ScalarProp1,
...
})
.AsQueryable();
return items;
}
I'm not sure if that will work the way you want it to, since I'm not familiar with Kendo Grid and such, but it may be useful.