get values from two tables in one single view by stored procedure in mvc - asp.net-mvc-4

My model is
public partial class Device
{
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Device_Id { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Device_Name { get; set; }
}
public partial class Customer
{
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_id { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Customer_Name { get; set; }
}
I want to display the values in both tables in one view i am using stored procedure to get the values..
I have written procedure to get the details from the 2 tables..I need the view to be like this.
<table >
<tr>
<th>Device </th>
<th>Customer Name</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.LabelForModel(item.Device_ModelNo)</td>
<td>#Html.LabelForModel(item.Customer_Name)</td>
</tr>
}
</table>

Create a Master class and include this two classes like this
public class Master
{
public Device device { get; set; }
public Customer customer { get; set; }
}
Now type your view with the master class
#model MasterModel

Related

Compare two lists and pass it to View

E-commerce website on ASP.NET Core 3.0
There are two model classes:
Products
Images
The multiple images of a single Product are stored in Images table. I am trying to create an All Products Page, but I am struggling with the logic of matching Image with Product Code and pass it to View which displays all the Products in shop along with thumbnail image from Images.cs and Product Title and its price from Product.cs table. How will I match data from two Model classes and make sure all the matching images and products are displayed relevantly.
Image.cs
public class Image
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ImageID { get; set; }
public string ProductCode { get; set; }
public virtual Product Product { get; set; }
public byte[] Pic { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
}
Product.cs
public class Product
{
public Product()
{
ICollection<Category> Categories = new HashSet<Category>();
ICollection<Image> Images = new HashSet<Image>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductID{ get; set; }
[Required, StringLength(150)]
public string ProductCode{ get; set; }
[Required, StringLength(150)]
public string Title { get; set; }
[StringLength(500)]
public string Description { get; set; }
public int Price { get; set; }
[StringLength(150)]
public string Type { get; set; }
[ForeignKey("Category")]
[Required]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Category> Categories { get; set; }
public virtual ICollection<Image> Images { get; set; }
}
Want to create something like this:
Something like this?
If you have relationships between products and images in database,
var list = _context.Product.Include(x => x.Image).ToList();
If you don't have relationship,
var imageslist = _context.Image;
var list = _context.Product.Select(x => new Product()
{
ProductId = x.ProductId,
Title = x.Title,
Price = x.Price,
Description = x.Description,
Images = imageslist.Where(y => y.ProductCode == x.ProductCode).ToList()
}).ToList();
then pass list to view and use #model List< Products > in your view to display all products.
EDITED 2
Your view page
#model IEnumerable<Product>
#{
foreach (var item in Model)
{
var base64image = Convert.ToBase64String(item.Images.FirstOrDefault().Pic);
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-3">
<table>
<tr>
<td>
<img src="data:image/png;base64,#base64image" height="100">
</td>
</tr>
<tr>
<td>#item.Title</td>
</tr>
<tr>
<td>#item.Price</td>
</tr>
</table>
</div>
}
}

Reference model class in controller, so muliple data can be in one view

I am trying to get data from multiple SQL Server stored procedure to be accessible in 1 view so I can then run comparisons and create graphs/grids etc.
I got each section to work on their own, and I am now trying to get them to work together.
I have change my controller and put the field types into their own classes, and then created a "Ring of Rings" class, and put them all in.
namespace APP.Models
{
public class SP_RESULTS
{
public type Type { get; set; }
public status Status { get; set; }
public condition Condition { get; set; }
public rooms Rooms { get; set; }
}
public class type
{
[Key]
public decimal type_id { get; set; }
public string type_code { get; set; }
public string type_name { get; set; }
}
public class status
{
//status
public decimal status_id { get; set; }
public string status_code { get; set; }
public string status_name { get; set; }
public string rentable { get; set; }
}
public class condition
{
//condition
public decimal condition_id { get; set; }
public string condition_code { get; set; }
public string condition_name { get; set; }
public string rentable { get; set; }
public int colour_code { get; set; }
public int service_order { get; set; }
}
public class rooms
{
//rooms
public decimal room_id { get; set; }
public string room_no { get; set; }
public decimal type_id { get; set; }
public int floor { get; set; }
public decimal status_id { get; set; }
public decimal condition_id { get; set; }
}
}
I then amended each section of my controller that was running SQL Server stored procedures, to use the correct class name instead of the "ring of rings" name, IE:
var outputmodel4 = new List<rooms>();
var command4 = db.Database.Connection.CreateCommand();
command4.CommandText = "SELECT rooms.room_id , rooms.room_no , rooms.type_id , rooms.floor_no , rooms.status_id , rooms.condition_id FROM rooms";
using (var SPOutput4 = command4.ExecuteReader())
{
foreach (var row in SPOutput4)
{
outputmodel4.Add(new rooms()
{
room_id = (decimal)SPOutput4["room_id"],
room_no = (string)SPOutput4["room_no"],
type_id = (decimal)SPOutput4["type_id"],
floor_no = (int)SPOutput4["floor_no"],
status_id = (decimal)SPOutput4["status_id"],
condition_id = (decimal)SPOutput4["condition_id"],
});
}
db.Database.Connection.Close();
return View(outputmodel4);
}
...etc for other SQL stored procedures
..and the same with my view
#model IEnumerable<app.Models.SP_RESULTS >
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Rooms.room_id)
</th>
<th>
#Html.DisplayNameFor(model => model.Rooms.room_no)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Rooms.room_id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rooms.room_no)
</td>
</tr>
}
</table>
…etc for the other models
Everything looks fine in VBS (no red swiggles), but when I access the view in the browser, I get an error:
Server Error in '/' Application.
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[app.Models.rooms]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[app.Models.SP_RESULTS]'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[app.Models.rooms]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[app.Models.SP_RESULTS]'.
If I go back to my "rings of rings" model, and change it to this :
public class SP_RESULTS
{
public IEnumerable<type> Type { get; set; }
public IEnumerable<status> Status { get; set; }
public IEnumerable<condition> Condition { get; set; }
public IEnumerable<rooms> Rooms { get; set; }
}
and change the following lines in in my controller:
var outputmodel4 = new List<rooms>();
outputmodel4.Add(new rooms()
to
var outputmodel4 = new List<SP_RESULTS>();
outputmodel4.Add(new SP_RESULTS()
VBS tells me that that
SP_RESULTS does not contain a definition for room_id
I've tried prefixing the definition with the class name, with no luck.
I've looked on SO, fourms.asp.net and google.. can cannot see a solution (there probably is, but I am unsure what solution I an looking for.... if that makes sense).
Would someone be able to tell me what I need to do to get all my model classes working in the same view ?
I apologise now, as I realize that this question has probably been asked several (million) times, but I cannot seem to fine out that jumps out says THIS is that way to do it.
For anyone else looking for an answer (and for future me), I got this work by putting the models like this :
namespace APP.Models
{
public class SP_RESULTS
{
public type Type { get; set; }
public status Status { get; set; }
public condition Condition { get; set; }
public rooms Rooms { get; set; }
public class type
{
[Key]
public decimal type_id { get; set; }
public string type_code { get; set; }
public string type_name { get; set; }
}
public class status
{
//status
public decimal status_id { get; set; }
public string status_code { get; set; }
public string status_name { get; set; }
public string rentable { get; set; }
}
public class condition
{
//condition
public decimal condition_id { get; set; }
public string condition_code { get; set; }
public string condition_name { get; set; }
public string rentable { get; set; }
public int colour_code { get; set; }
public int service_order { get; set; }
}
public class rooms
{
//rooms
public decimal room_id { get; set; }
public string room_no { get; set; }
public decimal type_id { get; set; }
public int floor { get; set; }
public decimal status_id { get; set; }
public decimal condition_id { get; set; }
}
}
}
Using VIEWDATA in the controller for each Store procedure:
var outputmodel3 = new List<SP_RESULTS.conditions>();
var command3 = db.Database.Connection.CreateCommand();
command3.CommandText = "dbo.pr_PROCEDUREONE";
command3.CommandType = System.Data.CommandType.StoredProcedure;
using (var SPOutput3 = command3.ExecuteReader())
{
foreach (var row in SPOutput3)
{
outputmodel3.Add(new SP_RESULTS.conditions()
{
condition_id = (decimal)SPOutput3["condition_id"],
condition_code = (string)SPOutput3["condition_code"],
condition_name = (string)SPOutput3["condition_name"],
});
}
ViewData["CONDITIONSOutput"] = outputmodel3;
}
var outputmodel4 = new List<SP_RESULTS.rooms>();
var command4 = db.Database.Connection.CreateCommand();
command4.CommandText = "SELECT rooms.room_id , etc FROM rooms";
using (var SPOutput4 = command4.ExecuteReader())
{
foreach (var row in SPOutput4)
{
outputmodel4.Add(new SP_RESULTS.rooms()
{
room_id = (decimal)SPOutput4["room_id"],
room_no = (string)SPOutput4["room_no"],
});
}
ViewData["ROOMSOutput"] = outputmodel4;
db.Database.Connection.Close();
return View();
}
..and then changing my view to read :-
table class="table">
<tr>
<th>
Condition ID
</th>
<th>
Condition code
</th>
<th>
Condition name
</th>
<th>
is it rentable?
</th>
<th>
Condition color code
</th>
<th>
Condition service order
</th>
<th></th>
</tr>
#foreach (var item in ViewData["CONDITIONSOutput"] as IEnumerable<Happ.Models.SP_RESULTS.conditions>)
{
<tr>
<td>
#item.condition_id
</td>
<td>
#item.condition_code
</td>
<td>
#item.condition_name
</td>
<td>
#item.rentable
</td>
<td>
#item.colour_code
</td>
<td>
#item.service_order
</td>
</tr>
}
</table>
<table class="table">
<tr>
<th>
Room ID
</th>
<th>
Room No
</th>
<th>
Rooms type_id
</th>
<th></th>
</tr>
#foreach (var item in ViewData["ROOMSOutput"] as IEnumerable<APP.Models.SP_RESULTS.rooms>)
{
<tr>
<td>
#item.room_id
</td>
<td>
#item.room_no
</td>
</tr>
}
</table>

Take data from different tables and display it in View Index in mvc4

I have 2 tables Work_table and Employee_table.I want to display emp_id from Work_table and corresponding emp_name from Employee_table in the index view of Employee_table.
my models are:
namespace MvcConQuery.Models
{
[Table("Work_Table")]
public class EnquiryModel
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int32 Enq_id { get; set; }
[Required]
[Display(Name="Name")]
public string CustomerName { get; set; }
[ReadOnly(true)]
public string Date
{
get
{
DateTime Date = DateTime.Now;
return Date.ToString("yyyy-MM-dd"); ;
}
set{}
}
[Required]
[Display(Name = "Region")]
public string Region { get; set; }
[Required]
[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone number format is not valid.")]
[Display(Name = "Phone number")]
public string Ph_No { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email_id")]
public string Email_id { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
[Required]
[Display(Name = "Query")]
public string Query { get; set; }
public string Referral { get; set; }
public string Feedback { get; set; }
public string Status { get; set; }
public Int32? Emp_id { get; set; }
public string FollowUpDate { get; set; }
public List<EmployeeModel> Employees { get; set; }
}}
namespace MvcConQuery.Models
{
[Table("Employee_Table")]
public class EmployeeModel
{
[Key,Column(Order=0)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
//[ForeignKey("EnquiryModel")]
public Int32 Emp_id { get; set; }
public string Emp_Name{ get; set; }
//[Key,Column(Order=1)]
public string Region { get; set; }
//[ForeignKey("Region")]
public string Emp_PhNo { get; set; }
public string Emp_Address { get; set; }
public List<EnquiryModel> Enquires { get; set; }
}
}
How to write controller?
I stucked when writing the function in controller.
public ActionResult Index()
{
}
Please suggest a solution. thanks in advance.
Regards
I was wrong earlier, I made out from your code that there is a many -to- many relationship between Employee and Work tables. For my convenience, I have used Job as the name for your Work table / model.
I hope that you want to display a list of EmployeeIds along with the corresponding EmployeeNames in the Index View. I have added an extra property called JobName to viewmodel, you can have other properties too.
For that matter, create a ViewModel EmployeeViewModel and bind the index view of your action result with an IEnumerable<EmployeeViewModel>. The definition for EmployeeViewModel can be something like -
public class EmployeeViewModel
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string JobName { get; set; }
//..Other memberVariables..
}
Suppose these are your models -
Employee
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public string Address { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
}
And WorkTable, renamed it as Job for my own convenience
public class Job
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int JobId { get; set; }
public string JobName { get; set; }
public JobCategory JobCategory { get; set; }
public int EmployeeId { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
In your Index Action, you create a result set by joining the two tables, bind it to IEnumerable<EmployeeViewModel> and pass that as a model to the view. The View should receive a model of type IEnumerable<EmployeeViewModel> as I mentioned earlier,so you need to query your entities which should be something like -
public ActionResult Index()
{
//..something like this..this is IQueryable..
//...convert this to IEnumerable and send this as the model to ..
//..the Index View as shown below..here you are querying your own tables,
//.. Employee and Job,and binding the result to the EmployeeViewModel which
//.. is passed on to the Index view.
IEnumerable<EmployeeViewModel> model=null;
model = (from e in db.Employees
join j in db.Jobs on e.EmployeeId equals j.EmployeeId
select new EmployeeViewModel
{
EmployeeId = e.EmployeeId,
EmployeeName = e.EmployeeName,
JobName = j.JobName
});
return View(model);
}
Your index view should be something like -
#model IEnumerable<MyApp.Models.EmployeeViewModel>
#{
ViewBag.Title = "Index";
}
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.EmployeeId)
</th>
<th>
#Html.DisplayNameFor(model => model.EmployeeName)
</th>
<th>
#Html.DisplayNameFor(model => model.JobName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.EmployeeId)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmployeeName)
</td>
<td>
#Html.DisplayFor(modelItem => item.JobName)
</td>
</tr>
}
</table>
In this above solution, I have made an attempt to generate a situation similar to yours and address your concerns. I hope this brings some sort of respite to your worries and helps you move ahead. Take this as a map and try follow the routes to find your own destination/solution. Btw, sorry for this delayed reply. Hope this helps.
This code has something missing select new EmployeeviewModel
model = (from e in db.Employees
join j in db.Jobs on e.EmployeeId equals j.EmployeeId
select new EmployeeViewModel
{
EmployeeId = e.EmployeeId,
EmployeeName = e.EmployeeName,
JobName = j.JobName
});

How to make this razor view working?

in my MVC web apps, this is the models which uses icollection object,
public class EmpProfile
{
public int EmpProfileID { get; set; }
public string EmpName { get; set; }
public string EmpNum { get; set; }
public string ManagerEditor { get; set; }
public string DocCreatedBy { get; set; }
public virtual ICollection<PerfPlan> PerfPlans { get; set; }
public virtual ICollection<ProgReview> ProgReviews { get; set; }
}
and this is PerfPlan model, the other model ProgReviews is similar like this one.
public class PerfPlan
{
public int ID { get; set; }
public int EmpProfileID { get; set; }
public string EmpName { get; set; }
public string EmpNum { get; set; }
public string Title { get; set; }
....
public virtual EmpProfile EmpProfile { get; set; }
}
Basically, it builds one to many relationship between EmpProfile and PerfPlan, ProgReview. So one EmpProfile has 0 or many Performance plan and Progress Review data (model).Now, in my Index razor of EmpProfile, I want to list all PerfPlan and ProgReview which related to each EmpProfile, I build something like this:
#model IEnumerable<PerfM.Models.EmpProfile>
<table>
#foreach (var item in Model)
{
<tr class="#selectedRow">
<td >
#Html.ActionLink(#item.EmpName, "Index", new { id = item.EmpProfileID })
</td>
</tr>
//here I need to list all PerfPlan and ProgReview related to this EmpProfile and list under this row.
Can any expert help me to continue the codes below?
Thanks a lot,
Just use simple foreach loops like this (inside of your foreach loop) :
foreach(var plan in item.PerfPlans)
{
// here you can access your PerfPlan properties like:
<tr>
<td> #plan.Id </td>
<td> #plan.EmpName</td>
<td> #plan.EmpNum </td>
...
</tr>
}
foreach(var review in item.ProgReviews)
{
...
}
And in your Controller don't forget to include your collections:
var profiles = context.EmpProfiles.Include("PerfPlans").Include("ProgReviews");

Two models in a view (with foreach)

I have two classes - Student.cs and Lecturer.cs placed under Models. Now that in my razor view I have to place two classes together.
I know there's a method Tuple to solve the problem. But I do not know what to do next. What should I do with my #foreach?
Here's my code in cshtml.
#model Tuple<MVCApp1.Models.Student, MVCApp1.Models.Lecturer>
#{
ViewBag.Title = "MainPage";
Layout = "~/Views/Shared/_Layout.cshtml";
}
I'm using a table, below is my #foreach code section.
#foreach (var j in Model)
{
<tr>
<td">#j.FirstName
</td>
<td>#j.MiddleName
</td>
<td>#j.LastName
</td>
I need to have 2 tables each with different attributes. First table from Student.cs and second table will be Lecturer.cs.
I know there is something wrong with the #foreach but I just can't find any solution online. Please help.
A tuple does not expose an iterator.
public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITuple
What you are after is a ViewModel.
public class ViewModel
{
public List<Student> Students { get; set; }
public List<Teacher> Teachers { get; set; }
}
public ActionResult Index()
{
ViewModel model = new ViewModel();
// retreive from database
model.Students = new List<Student>() { new Student()};
model.Teachers = new List<Teacher>() { new Teacher()};
return View(model);
}
Then you can structure your table
<table>
<tr>
<th>First</th>
<th>Middle</th>
<th>Last</th>
</tr>
#foreach (var student in Model.Students)
{
<tr>
<td>#student.First</td>
<td>#student.Middle</td>
<td>#student.Last</td>
</tr>
}
#foreach (var teacher in Model.Teachers)
{
<tr>
<td>#teacher.First</td>
<td>#teacher.Middle</td>
<td>#teacher.Last</td>
</tr>
}
</table>
Once you are comfortable with this, you can explore inheritance and Entity Framework TPH Table per hierarchy.
You could end up with something like this:
public abstract class Person
{
public int Id { get; set; }
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
}
public class Teacher : Person
{
public string Class { get; set; }
public DateTime HireDate { get; set; }
}
public class Student : Person
{
public int Grade { get; set; }
public DateTime EnrolledDate { get; set; }
}
public class ViewModel
{
public List<Student> StudentsOnly { get; set; }
public List<Person> StudentsAndTeachers { get; set; }
}
public ActionResult Index()
{
Context db = new Context();
ViewModel model = new ViewModel();
// You could collect just the students
model.StudentsOnly = db.People.OfType<Student>().ToList();
// Or all of them
model.StudentsAndTeachers = db.People.ToList();
return View(model);
}
Then you would only have to iterate through the single list of people, if you only needed to display their names.
<table>
...
#foreach (var person in Model.StudentsAndTeachers)
{
<tr>
<td>#person.First</td>
<td>#person.Middle</td>
<td>#person.Last</td>
</tr>
}
</table>