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.
Related
I'm building a website in ASP.Net, using MVC, and need to list a set of results
but i get error in the code
model:
public class Customers
{
public int Id { get; set; }
public string Name { get; set; }
public List<Customers> Itemlst { get; set; }
}
controller:
public ActionResult List()
{
Customers itemobj = new Customers();
return View(itemobj);
}
view:
#foreach(var item in Model.Itemlst)
{
<tr>
<td>Items ID:</td>
<td>#item.ID</td>
<td>Items Name:</td>
<td>#item.Name</td>
</tr>
}
</table>
From the NullReferenceException that you are receiving we can see that the issue is because of the Itemlst not being initialised. One of the ways to solve this is just to make sure that there is a valid list when you create the object:
public class Customers
{
public Customers()
{
Itemlst = new List<Customers>();
}
public int Id { get; set; }
public string Name { get; set; }
public List<Customers> Itemlst { get; set; }
}
So you can add values to the list in your action if need:
public ActionResult List()
{
Customers itemobj = new Customers();
var example = new Customers ();
example.Id = 1;
example.Name = "Example";
itemobj.Add();
return View(itemobj);
}
I don't know if you are just using this as an example for your question, but I can't help but notice that there is something weird. You could use something different like:
public class ViewModel // Name to what makes sense to you
{
// Some other properties...
public List<Customer> Customers { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
Or you could just use List<Customer> as your model in the view directly (yes, your model can be a object which is simply a list of objects).
When you pass the Customers list to the view, this list itself is the model.
Change Model.Itemlst —> Model inside the foreach loop.
This will iterate the list of customers.
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; }
}
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>
I want to access image from database direct in razor view.
This is my code
#model IEnumerable<TelerikMvcAppCombo.Models.ImageModel>
#{
Layout = null;
}
#foreach (var image in Model)
{
<img src=#image.IMAGESIZE_DESC/>
}
This is my model Class:-
[Table("IMAGESIZE")]
public class ImageModel
{
[Key]
public int IMAGESIZE_ID { get; set; }
public string IMAGESIZE_NAME { get; set; }
public string IMAGESIZE_DESC { get; set; }
public int created_by { get; set; }
public DateTime created_date { get; set; }
public int modified_by { get; set; }
public DateTime modified_date { get; set; }
}
This is my Controller Class:-
public JsonResult GetData([DataSourceRequest] DataSourceRequest request)
{
var list = db.imageModels.ToList();
return Json(list.ToDataSourceResult(request));
}
I don't know what's your problem exactly but try this:
#foreach (var image in Model)
{
<img src="#Url.Content(image.IMAGESIZE_DESC)" />
}
I don't know your view name but I assume that It is GetData.
You have to return ViewResult instead of JsonResult. You are returning JsonResult so it is not working.
public ActionResult GetData([DataSourceRequest] DataSourceRequest request)
{
var list = db.imageModels.ToList();
return View(list.ToDataSourceResult(request));
}
If you want to use JsonResult then you have to get data client side and bind them client side and in that case Razor view is not working.
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
}