ASP.MET MVC Multiple Model in One View - asp.net-mvc

I want to use multiple model in one view, I red some article to use complex Model, or Partial View, or Viewbag and other,but couldn't find normal answer.
I want to display data from different models.
Here is my Models
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public string Image { get; set; }
public IEnumerable<Teacher> Teachers { get; set; }
}
public class Teacher
{
public int TeacherID { get; set; }
public string TeacherName { get; set; }
public string TeacherLname { get; set; }
public int DepartmentID { get; set; }
public string Image { get; set; }
public Department Department { get; set; }
}
public class ClassOut
{
public int Id { get; set; }
public string ClassOutName { get; set; }
}
public class SchoolDbContext:DbContext
{
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<ClassOut> ClassOuts { get; set; }
}

Combine all your models in one common view model and use it in your view.
public class ViewModelName
{
public Department Department {get; set;}
public Teacher Teacher {get; set;}
public ClassOut ClassOut {get; set;}
}
Use this model for your view:
#model ViewModelName
......
#Html.TextBoxFor(x => x.Teacher.TeacherName )
.....
And in your post action method
public ActionResult MethodName(ViewModelName viewModel)
{
//
}

Try to create a Class ( for example Manager) where you add a variable for Department, ClassOut, ClassOutName and then you pass the Class Manager to the view and then you can access easily
public class Manager
{
public Department dept;
public ClassOut cl;
public ClassOutName clname;
}

Related

posting customer details with 'n ' no of address

I have two model classes "customerdetails" and "addresssdetails".my question is "one customer can save with multiple addresss?
namespace customer2.Models
{
public class customerdetails
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { set; get; }
[Key]
public int customerid { set; get; }
public string customername { set; get; }
}
public class addressdetails
{
public int addressno { set; get; }
public string street { set; get; }
public string landmark { set; get; }
public int pincode { set; get; }
}
public class MkContext : DbContext
{
public virtual DbSet<customerdetails> customers { get; set; }
public virtual DbSet<addressdetails> address { get; set; }
}
public class customerviewmodel
{
public customerdetails cd { set; get; }
public List<addressdetails> ad { set; get; }
}
}![enter image description here](https://i.stack.imgur.com/4QCA1.jpg)
Before I answer, just a quick tip:
Make sure to properly case your class names and properties to improve readability.
Here is a link with some guidelines
If you want to store a Customer with multiple AddressDetails, you will need to define a class and add it to the context.
public class Customer {
public int Id { get; set; }
public CustomerDetails CustomerDetails { get; set; }
public IList<AddressDetails> AddressDetails { get; set; }
}
Then add this to the context.

How can i use two models in same controller(EntityFramwork) and use each in different action?

I have made one model so far and added controller using EF, and made some list of books
public class Books
{
public string ImageUr { get; set; }
public string BookTitle { get; set; }
public string ShortDescription { get; set; }
public decimal Price { get; set; }
public string Author { get; set; }
public int ID { get; set; }
}
public class BooksDBContext : DbContext
{
public DbSet<Books> Book { get; set; }
}
and im displaying that list in this action:
public ActionResult Books()
{
return View(db.Book.ToList());
}
and my question is how can i make another model or database that will be passed into this action (viewpage for news about new books for example):
public ActionResult News()
{
View(db.News.ToList());
}
and the model for news to be something like this:
public class News
{
public string Title{ get; set; }
public string Subtitle { get; set; }
public string Content{ get; set; }
public int ID { get; set; }
}
Well maybe you can try out a viewmodel. When I started learning ASP.NET MVC I did the tutorial Working with data and learned a lot about entity framework and ASP.NET MVC! I will give you a link. ASP.NET working with data
For your solution some code:
UPDATE You will need some virtual properties in your classes to define the relationships: we have a one to many relationship because book can have more news items and news can only have one book.
public class Book //change your class name to book
{
public string ImageUr { get; set; }
public string BookTitle { get; set; }
public string ShortDescription { get; set; }
public decimal Price { get; set; }
public string Author { get; set; }
public int ID { get; set; }
public int NewsId { get; set; }
public virtual ICollection<News> News { get; set; }
}
public class News
{
public string Title{ get; set; }
public string Subtitle { get; set; }
public string Content{ get; set; }
public int ID { get; set; }
public int BookId {get; set; }
public virtual Book Book { get; set; }
}
if your want to use a viewmodel then add a new folder named viewmodels and add a new class
public class BookNewsViewmodel //viewmodel of book and News :)
{
public IEnumerable<Book> Books { get; set; }
public IEnumerable<News> News { get; set; }
}
In the DbContext
namespace yourProject.DAL
{
public class yourProjectContext : DbContext //this is a DbContext!
{
public yourProjectContext () : base("yourProjectContext") //A constructor
{
}
public DbSet<Book> Books { get; set; } //make a DbSet of your classes
public DbSet<News> News { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Pluralize your tablenames from Books to Book and from Newss to News :)
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
In your controller:
With viewmodel
public ActionResult BookNewsIndex()
{
var viewModel = new BookNewsViewmodel();
viewModel.Books = db.Books
.Include(n => n.News)
return View(viewModel.ToList()); //return your data.ToList() to your view
}
Without a viewmodel
public ActionResult BookNewsIndex()
{
var data = db.Books.Include(n => n.News);
return View(data.ToList()); //return your data.ToList() to your view
}
In your View named BookNewsIndex you can do this. I am not sure about this but you can give it a try
#model yourproject.ViewModels.BookNewsViewmodel for your viewmodel
OR
#model IEnumerable<yourProject.Models.Book> without viewmodel
with viewmodel
#model.Books.ShortDescription
#model.News.Subtitle
without viewmodel
#Model.First().ShortDescription get something from your book!
#Model.First().News.First().Subtitle get something from news!
In part 7 of the tutorial he will use a viewmodel
I hope this will help you!
This has nothing to do with MVC, but with Entity Framework.
You'll have to add the DbSet for News:
public class BooksDBContext : DbContext
{
public DbSet<Books> Book { get; set; }
public DbSet<News> News { get; set; }
}

Creating list in View to add to Model's ICollection property

I am trying to create a website that allows user to upload recipe
So I have a model class called Recipe and it looks like following
[Table("Recipe")]
public class Recipe
{
public int ImageMimeType { get; set; }
public byte[] Thumbnail { get; set; }
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RecipeID { get; set; }
public string BakeryName { get; set; }
public string Description { get; set; }
public byte[] ImageData { get; set; }
public int EndorsementCount { get; set; }
public DateTime LastModified { get; set; }
[Required]
public int UserId { get; set; }
public virtual ICollection<Ingredient> Ingredients { get; set; }
public virtual ICollection<Method> Methods { get; set; }
}
and my Ingredient class looks like follow:
[Table("Ingredient")]
public class Ingredient
{
[Key]
public int IngredientID { get; set; }
[Required]
public int RecipeID { get; set; }
public string ItemName { get; set; }
public int Measurement { get; set; }
public string MeasurementUnit { get; set; }
}
And in my View I want to add ingredient dynamically: User click an 'add' button to add another ingredient when she wants to.
My questions are:
How should I create a list in my View for the ingredients and pass it to my Controller's Create method when I submit my form?
And the problem is, as the RecipeID is Autogenerated, I don't know what my RecipeID is going to be while in the View until I save my Recipe in the database table. But how to I pass this RecipeID to each of my Ingredients?
Any help will be very much appreciated!

use two models in one view

net MVC 5 I have a view that require info from two models. In one modelView i have Student Marks and in the other, I have Student details How do I call both models to the view.
public class Student
{
[Key]
public int StudentNum { get; set; }
public string StudentName { get; set; }
public string StudentSurname { get; set; }
public string Email { get; set; }
}
public class Marks
{
[Key]
public int Mark1 { get; set; }
public int Mark2 { get; set; }
public int Dp { get; set; }
public int StudentNum { get; set; }
public virtual Student Student { get; set; }
}
Create a new View Model which encapsulates both the other view models as,
public class StudentViewModel
{
public Details Details { get; set; }
public Marks Marks { get; set; }
}
and pass it to the view you use. And access by Model.StudentViewModel.Details for getting student details and for marks Model.StudentViewModel.Marks.

Join two model to present in a view in MVC

I want to join two below model class with entity framework in controller for present factor in accounting system in a view
<pre>
namespace AccountingSystem.Models
{
public class BuyFactor
{
public int BuyFactorId { get; set; }
public DateTime CreateDate { get; set; }
public string Seller { get; set; }
public string Creator { get; set; }
public decimal SumAllPrice { get; set; }
public ICollection<BuyFactorDetail> BuyFactorDetails { get; set; }
}
}
namespace AccountingSystem.Models
{
public class BuyFactorDetail
{
public int BuyFactorDetailId { get; set; }
public int Number { get; set; }
public string Description { get; set; }
public decimal SumPrice { get; set; }
public int BuyFactorId { get; set; }
public virtual BuyFactor BuyFactor { get; set; }
public virtual Commodity Commodity { get; set; }
}
}
</pre>
Create a new Model
public class JointModel
{
public BuyFactor BuyFactor {get; set;}
public BuyFactorDetail BuyFactorDetail {get; set;}
}
Just create another model then calls the other model in there
public class ParentModel
{
public BuyFactor BuyFactor {get; set;}
public BuyFactorDetail BuyFactorDetail {get; set;}
}
So when you will call it in view
#model IEnumerable<AccountingSystem.Models.ParentModel>
#Html.DisplayNameFor(model => model.BuyFactor.Creator)
Best way define Model as a Property in Main Model
For example
public class BuyFactor
{
public int BuyFactorId { get; set; }
public DateTime CreateDate { get; set; }
public string Seller { get; set; }
public string Creator { get; set; }
public decimal SumAllPrice { get; set; }
public ICollection<BuyFactorDetail> BuyFactorDetails { get; set; }
public BuyFactorDetail BuyFactorEntity {get;set;}
}
Assign value in BuyFactorEntity and use as Model.BuyFactorEntity.BuyFactorDetailId
Use a Linq join query like
var query = (from b in context.BuyFactors
join d in context.BuyFactorDetail
on
..
select new
{
BuyFactorId = b.BuyFactorId,
....
BuyFactorDetailId = d.BuyFactorDetailId,
...
..
}));
Your BuyFactor already contains the BuyFactorDetail collection. You sure the entities are 1:N relationship with each other?
You can use the BuyFactor as model and could use the BuyFactorDetails propertu of the BuyFactor entity.
Use ViewBag in controller to assign respective objects for both.
ViewBag.BuyFactor= BuyFactor;
ViewBab.BuyFactorDetail = BuyFactorDetail;
To use it in view you will have to typecast them back.

Resources