Using Multiple model in a single view ASP.NET, MVC [duplicate] - asp.net-mvc

This question already has answers here:
Multiple models in a view
(12 answers)
Closed 6 years ago.
I am devolaping a 2nd hand item selling like OLX, I have two models
1: Product_model
2: Customer_model
so i want to use the the product description and customer information in a single view.
Models:
[Table("Product")]
public class ProductModel
{
[Key]
public string ProductId { get; set; }
public string ProductName { get; set; }
public decimal ProductPrice { get; set; }
public string ProductDescription { get; set; }
public string ProductCategory { get; set; }
public string ProductAddress { get; set; }
public string ProductImage1 { get; set; }
public string ProductImage2 { get; set; }
public string ProductImage3 { get; set; }
public string CustomerId { get; set; }
// public DateTime ProductSubTime { get; set; }
}
[Table("Customer")]
public class CustomerModel
{
[Key]
[Required(ErrorMessage = "Please provide Customer ID",
public string CustomerFullName { get; set; }
public int CustomerContact { get; set; }
public string CustomerEmail { get; set; }
public string CustomerGender { get; set; }
public string CustomerAddress { get; set; }
}
My controller:
public ActionResult Index()
{
return View(cm.Products.ToList());
}
My view:
#model IEnumerable<WebApplication11.Models.ProductModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/MyTemplate.cshtml";
}
<div class="col-md-4"style="border: 2px solid yellow" >
<div class="single-product-widget" style="border: 2px solid black">
<h2 class="product-wid-title">Recently Viewed</h2>
View All
#{ int i = 0;}
#foreach (var item in Model)
{
<div class="single-wid-product" style="border: 2px dashed black">
<img src="~/images/#item.ProductImage1" alt="No Photo" class="product-thumb">
<h2>#Html.DisplayFor(model => item.ProductName)</h2>
</div>
}
<div>
</div>
For understanding purpose i deleted some part of view.
Please guide me accessing both models in particular view.
I tried also some methods but not able to get it.
Thanks in advance...

You can create a view model with 2 properties like following code
public class MyModel
{
public List<ProductModel> Products { get; set; }
public List<CustomerModel> Customers { get; set; }
}
In controller:
public ActionResult Index()
{
var model = new MyModel
{
Products = cm.Products.ToList(),
Customers = cm.Customers.ToList()
};
return View(model);
}
In Veiw
#foreach (var item in Model.Products)
{
#*Write your razor code here*#
}

There are several options to access several models in a particular view. I assume that you just want to show some customer information in page corner or something. Your layout view may have a requirement to include this customer info (but it does not matter anyway).
Most preferable option from my point of view is to use child action.
Create CustomerController
public class CustomerController : Controller {
[ChildActionOnly]
public ViewResult CustomerInfo() {
CustomerModel customer = ...
return PartialView("_CustomerPartial", customer);
}
}
.chstml view will have #Html.Action("CustomerInfo", "Customer") where you want customer info to be displayed.
This way you will have a separate CustomerModel creation logic.
Another option is to use ViewData or ViewBag to store secondary model information like customer info.
Controller code:
public ActionResult Index()
{
var products = cm.Products.ToList();
ViewBag.Customer = ... // get customer
return View(products);
}
View code:
#model IEnumerable<WebApplication11.Models.ProductModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/MyTemplate.cshtml";
var customer = (CustomerModel)ViewBag.Customer;
}
#* display customer info *#
#* either { *#
<div>Welcome #customer.CustomerFullName. You email is #customer.CustomerEmail</div>
#* } or { *#
#Html.Partial("_CustomerPartial", customer)
#* } *#
#foreach(var product in Model) {
#* display product info *#
}
Previous option can be changed in a way to use strongly typed model. It is also can be known as view model - usually a class that exists only to store necessary info for the view. In your case these are some customer and products information.
ViewModel:
public class ProductListViewModel {
public CustomerModel Customer { get; set; }
public IEnumerable<ProductModel> Products { get; set; }
}

Related

how to pass the count of related model class to view page in asp.net MVC

i have created 2 model classes Mocmodel and mocsubmodel and set navigation property also.for each model id, there will be different submodels for a particular model id. i wanted to create am action link showing count of submodels, when i click on the count, view should display submodel details for each particular modelIDs like below
1220 FXRate count as hyperlink
public class tModel
{
public int ModelID { get; set; }
public string ModelName { get; set; }
public virtual ICollection<tSubModelcs> submodellist { get; set; }
}
public class tSubModelcs
{
public int submodelID { get; set; }
public string submodel { get; set; }
public DateTime launchdate { get; set; }
public int ModelID { get; set; }
}
in my view page i want to display the count of submodel as a link
#foreach (var m in Model)
{
<tr>
<td>#m.ModelID</td>
<td>#m.ModelName</td>
<td>
Html.ActionLink(, "findsubmodels", new { #id = m.ModelID, #class = "linkclick" })
</td>
</tr>
Nothing is clear. Which model are you sending to view ? Post your complete code with action methods. It seems like you are sending IEnumerable of tModel. If this is the case your Actionlink should be like this.
#if(m.submodellist != null)
{
#Html.ActionLink(m.submodellist.Count.ToString(), "findsubmodels",null, new { id = #m.ModelID, #class = "linkclick" })
}
Replace the null with your routevalue if any.

Implement a collection of an object in my view model - ASP.net MVC

I'm Completely new in ASP.net MVC
I have two model first is category
public class Category
{
public virtual int Id { get; set; }
[Required]
public virtual string CategoryName { get; set; }
public virtual List<SubCategory> SubCategories { get; set; }
}
and next subcategory model:
public class SubCategory
{
public virtual int Id { get; set; }
public virtual int CategoryId { get; set; }
[Required]
public virtual string SubCategoryName { get; set; }
public virtual Category Category { get; set; }
public virtual List<Question> Questions { get; set; }
}
I need to have a list of my categories and also a list of subcategories both in my view so this is my view model
public class CategorySubCategoryViewMoel
{
public ICollection<Category> Category { get; set; }
public SubCategory SubCategory { get; set; }
}
and here is my view
#model FinalSearch5.Models.CategorySubCategoryViewMoel
<ul>
#foreach (var category in Model.Category)
{
<li>#category.CategoryName</li>
}
</ul>
here is my controller
public ActionResult Index()
{
var cats = db.Categories.ToList();
return View(cats);
}
It's not implementing completely yet but until here there is an Error
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[FinalSearch5.Models.Category], but this dictionary requires a model item of type 'FinalSearch5.Models.CategorySubCategoryViewMoel'.`
Appreciate if help me what is the problem thank you.
You view expects a model which is typeof CategorySubCategoryViewMoel but in the Index() method, you return a model which is List<Category>. In order for it to work, you could change the method to
public ActionResult Index()
{
var model = new CategorySubCategoryViewMoel
{
Category = db.Categories.ToList()
}
return View(model );
}
Note that the property is a collection, so its name should be pluralized, and need only be IEnumerable i.e. public IEnumerable<Category> Categories { get; set; }
However its unclear what the purpose of your view model is. Its only other property is public SubCategory SubCategory { get; set; } and you never assign a value to it, or use it in the view. You code could use your current Index() method and then the view would be
#model List<Category>
<ul>
#foreach(var category in Model)
{
<li>
#category.CategoryName
<ul>
#foreach(var subCategory in category.SubCategories)
{
<li>#subCategory.SubCategoryName</li>
}
</ul>
<li>
}
<ul>

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
}

asp.net mvc rendering partial view on-demand

I'm a newbie to asp.net mvc and I'd like to know if what I do is correct.
I want to create a view for searching people. Here's what I have so far:
The business model class:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public DateTime DOB { get; set; }
public List<Telephone> Telephones { get; set; }
}
The ViewModel class:
public class SearchPersonViewModel
{
public int Id { get; set; }
public string FullName { get; set; }
public string LicencePlate { get; set; }
public string CarMake { get; set; }
public string CarModel { get; set; }
}
The partial view :
#model IEnumerable<MvcApplication2.Models.SearchPersonViewModel>
#foreach (var item in Model)
{
#Html.DisplayFor(m => item.Id)
#Html.DisplayFor(m => item.FullName)
}
The view from which the partial view is called:
#Html.Action("Search", "Person");
*The controller method in the PersonController:
[ChildActionOnly]
public ActionResult Search()
{
List<SearchPersonViewModel> model = new List<SearchPersonViewModel>();
model.Add(new SearchPersonViewModel() { FullName = "test", Id = 3 });
return PartialView("_SearchPerson", model);
}
Now the problem is that the Search method is called whenever the main View is loaded. What I want is to add a search textbox on the mainview for filtering the collection rendered in the partial view. How could I do that ?
This way your partial will render on click only
<script>
(function($){
$('#btn').click(function(){
$('#searchresult').load('#Url.Content("~/Person/Search")');
}
</script>
Make an ajax request to /search and append the data to your page.
<div id = 'searchresult'>
#Html.Action("Search", "Person");
</div>
whenever your want to filter call something like $('#searchresult').load('/search?q=xxx');
You could use 2 ways:
microsoft ajax helpers
jquery
For both of them you need to remove [ChildActionOnly] and #Html.Action("Search", "Person");
Look at this example: Using Ajax.BeginForm with ASP.NET MVC 3 Razor

How can a single view access multiple models in mvc3

i am developing an application in MVC3.
Basically it is an Question Forum where on Question page user will see all questions as link and a post comment box at the end.and when he clicks on question link he is moved to the answers page.now the answer page is using another model class and their i am not able to acess my answer class data
what i found was every Controller has a view and a model
but i want my view to access multiple models and i dont knw how to go about it..
I tried this:
public class MainClass
{
public Question_Page question{ get; set; }
public Answer_Page answer { get; set; }
}
public class Question_Page
{
public virtual int Id { get; set; }
public virtual string Question_name { get; set; }
public virtual DateTime Created_Date { get; set; }
public virtual DateTime Modified_Date { get; set; }
public virtual int Created_By { get; set; }
public virtual int Modified_By { get; set; }
public virtual char Deleted { get; set; }
public Question_Page()
{
this.Deleted='F';
}
}
public class Answer_Page
{
public virtual int Id { get; set; }
public virtual string Answer { get; set; }
public virtual DateTime Created_Date { get; set; }
public virtual DateTime Modified_Date { get; set; }
public virtual int Created_By { get; set; }
public virtual int Modified_By { get; set; }
public virtual char Deleted { get; set; }
public virtual Question_Page Question { get; set; }
public Answer_Page()
{
this.Deleted='F';
}
}
Now inside the view of Questions List where i display a list of questions:
#model IEnumerable<Core.Model.MainPage>
#{
ViewBag.Title = "Index";
}
<style type="text/css">
ul
{
list-style-type: none;
}
</style>
<h2>All Questions</h2>
<hr />
#using (Html.BeginForm("Index","Question",FormMethod.Post))
{
#Html.ValidationSummary(true)
<ul>
#foreach (var item in Model)
{
<li>#Html.ActionLink(item.Question_name, "answer", new { Qry = item.Id })</li>
}
</ul>
<label for="PostyourQuestion:">Post your Question:</label><br /><br />
#Html.TextArea("textID")
<br />
<input type="submit"/>
}
after doing this much i am gettin errorin line:
#foreach (var item in Model)
This is my controller:
public ActionResult Index()
{
return View(new StudentService().GetAllStudents());
}
[HttpPost]
public ActionResult Index(Question_Page question,string textID)
{
question.Question_name = textID;
question.Created_Date = DateTime.Now;
question.Modified_Date = DateTime.Now;
question.Created_By = 101;
question.Modified_By = 101;
new StudentService().SaveOrUpdateStudent(question);
return View(new StudentService().GetAllStudents());
}
StudentService is a class where i hv defined the methods GetAllStudents(),SaveOrUpdateStudent()
Please help me
Your answer is rather simple I think?
#foreach (var item in Model)
should be
#foreach (var item in Model.Question_Page)
Your model is MainPage?
can you post that model here as well?
assume that GetAllStudents() return IEnumerable<Student>
in your controller
return View(new StudentService().GetAllStudents());
the actual Model send to View is IEnumerable<Student>
if you need IEnumerable<Core.Model.MainPage> as Model just return proper objects from your controller
IEnumerable<Core.Model.MainPage> model = //... define function that return Enumerable MainPage
return View(model);
If You want to use the same model on different views
public ActionResult Index()
{
//I am assuming, You are returning IEnumerable<MainClass>
List<MainClass> mainClass=new StudentService().GetAllStudents();
if(mainClass==null)
mainClass=new List<MainClass>(); //Incase you are not checking null value return
return View(mainClass); //return a none null IEnumerable<MainClass> object
}
[HttpPost]
public ActionResult Index(Question_Page question,string textID)
{
question.Question_name = textID;
question.Created_Date = DateTime.Now;
question.Modified_Date = DateTime.Now;
question.Created_By = 101;
question.Modified_By = 101;
new StudentService().SaveOrUpdateStudent(question);
return View(new StudentService().GetAllStudents());
}
Once your first controller method works, you will need to work on binding your model, for the second post method to work.
try viewModel. A model that have references to your desired model. so if a view is bound to your view model, then all the models referenced in the ViewModel will also get bonded.

Resources