I want to use two models in one View. Here is my code:
public class Users {
public int id { get; set; }
public string adSoyad { get; set; }
public string email { get; set; }
public int puan { get; set; }
}
public class admin {
public int id { get; set; }
public string name { get; set; }
}
public class mainmodel {
public Users Users { get; set; }
public admin admin { get; set; }
}
I can use it to delete, edit, and create views. But I get errors in my index view:
#model IEnumerable<donemProje.Models.mainmodel>
What can I do?
Edit--
i try this in index view
#model donemProje.Models.mainmodel
#foreach (var item in Model.Users)
{
<tr>
<td>
#Html.DisplayFor(modelItem =>item.adSoyad)
</td>
<td>
#Html.DisplayFor(modelItem => item.email)
and get this error
Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'donemProje.Models.Users' because 'donemProje.Models.Users' does not contain a public definition for 'GetEnumerator'
int this line
Line 34: #foreach (var item in Model.Users)
Your model in the view should be #model mainmodel
If you want to use two models in one view, you should use ViewModels (A class which consists of other classes which are used in view)
#model IEnumrable or you tried #model IeEnumrable<mainmodel> ? if you tried #model IEnumrable<mainmodel> than mainmodel have list of users and admin in it. but what i understand from your question i think the below words will help you.
You can try #model mainmodel and you can iterate through mainmodel using foreach loop.
foreach(var user in Model.Users)
{
// you code goes here..
}
and same thing for the admin if want to iterate through admin. else just use #Model.Admin.id
Related
I have some entities, Products, and Categories. I need to call the category name instead of the category ID. When I try to call the name, I get this error:
An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
sistemaFacturacion.Components.Products.ListProductComponent.BuildRenderTree(RenderTreeBuilder __builder) in ListProductComponent.razor, line 22
This is the code I use to call the category name.
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Nombre</th>
<th>Cantidad</th>
<th>Categoria</th>
<th>Accion</th>
</tr>
</thead>
<tbody>
#foreach (var product in tempProducts)
{
<tr>
<td>#product.ProductId</td>
<td>#product.Name</td>
<td>#product.Units</td>
<td>#product.Category.Name</td> //HERE IS THE ERROR LINE
<td>
<a type="button"
class="btn btn-primary"
href="">Editar</a>
</td>
</tr>
}
</tbody>
</table>
#code {
List<ProductsEntity> products = new List<ProductsEntity>();
List<ProductsEntity> tempProducts = new List<ProductsEntity>();
List<CategoriesEntity> Category = new List<CategoriesEntity>();
protected override async Task OnInitializedAsync()
{
products = B_Product.ProductList();
tempProducts = products;
Category = B_Category.CategoryList();
}
}
These are the entities:
namespace EntitiesApp
{
public class CategoriesEntity
{
[Key]
public int CategoryId { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
//Relation with Products
public ICollection<ProductsEntity> Products { get; set; } // 1 to N
}
}
This is the users entity
namespace EntitiesApp
{
public class ProductsEntity
{
[Key]
public int ProductId { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Required]
public int Units { get; set; }
[Required]
public float Price { get; set; }
public Nullable <float> Cost { get; set; }
[MaxLength(100)]
public string SKU { get; set; }
//Relation with Categories - Relation 1 to 1
public int CategoryId { get; set; }
public CategoriesEntity Category { get; set; }
}
}
I'm not sure what's the issue...
Thanks for your time :)
You got 'NullReferenceException' therefore you probably forgot to perform the load data operation in EF. If you want to use any Navigation Property like 'Category' in your code you need to load related data.
You have to make sure you have loaded Category for the ProductsEntity. You can't directly use it by default. If you want to use it without loading, you can use 'Lazy Loading' but this isn't default approach of EF. On the other hand, 'Eager Loading' method is suitable in general.
Look at this => https://learn.microsoft.com/en-us/ef/core/querying/related-data/
By the way, I can give you some tips to quick fix. In your code, There is 'B_Product' but it's unclear where this came from as I can't see the full code. Assume that you can reach all your DbSets like 'ProductsEntity' and 'CategoriesEntity' in _context. In addition instead of 'ProductsEntity', you can simply call it 'Product'. This way it will be shorter and more concise.
Assume that this is your Context class and these are your DbSets
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
After performing the operation below, you will be able to access the 'category' Navigation Property over a 'Product' Model.
private readonly DbContext _context;
_context.Products.Include(p => p.Category).ToList();
On the other hand, I assumed you were using Entity Framework. But maybe you didn't use database and you get the data through a collection. In this case, the logic would still be the same. Before using 'category' over Product Model in your .cshtml file, you must load the relevant data into it.
I am new to ASP.NET MVC 5.
On debug mode, I saw some values being looped to the partial view but in UI no values are being displayed.
My Model
public class Model
{
public int ID { get; set; }
public string UserID { get; set; }
public List<ReferenceModel> ReferenceModelList{ get; set; }
}
My Controller
public ActionResult GetModel(string dataobject, int id = 0)
{
Model model = new Model();
model = BL.GetModel(dataobject, id);
return PartialView("_ReferenceModelList", model);
}
ReferenceModelList(PartialView)
#model Web.Model.Model
#{
Layout = null;
}
#foreach (var menurefitem in Model.ReferenceModelList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => menurefitem.Code)
</td>
<td>
#Html.DisplayFor(modelItem => menurefitem.Description)
</td>
</tr>
}
Partial View Data in VS:
Please help.
You need to call the Controller method from you main UI like this
#{Html.RenderAction("GetModel","SAPSecurity");}
At first you should instantiate your list at the constructor of your class.I think your problem should be solved.
public class Model
{
public Model()
{
ReferenceModelList=new List<ReferenceModel>();
}
public int ID { get; set; }
public string UserID { get; set; }
public List<ReferenceModel> ReferenceModelList { get; set; }
}
This question already has answers here:
The model item passed into the dictionary is of type .. but this dictionary requires a model item of type
(7 answers)
Closed 5 years ago.
I'm trying to Create Poll System but there some issue.
I have to classes generate it by ADO.NET Entity Framework
Second I create Repository class to work with it from my controller class
I create ActionResult Method in my PollController class that return All the Pool Questions from my DataBase.
I have one Particle View I create it to show the option for specific question
When I put this particle in my Index.cshtml it give me this error The model item passed into the dictionary is of type 'System.Collections.Generic.List
here is my code
Poll.cs
public partial class Poll
{
public Poll()
{
this.PollOptions = new HashSet<PollOption>();
}
public int PollID { get; set; }
public Nullable<System.DateTime> AddedDate { get; set; }
public string AddedBy { get; set; }
public string QuestionText { get; set; }
public bool IsCurrent { get; set; }
public bool IsArchived { get; set; }
public virtual ICollection<PollOption> PollOptions { get; set; }
}
PollOption.cs
public partial class PollOption
{
public int OptionID { get; set; }
public Nullable<System.DateTime> AddedDate { get; set; }
public string AddedBy { get; set; }
public string OptionText { get; set; }
public int PollID { get; set; }
public Nullable<int> Votes { get; set; }
public virtual Poll Poll { get; set; }
}
PollRepository.cs
public class PollRepository
{
private PollPlatFormEntities entities = new PollPlatFormEntities();
public IQueryable<Poll> GetPolls()
{
return entities.Polls;
}
public Poll GetPoll(int Id)
{
return entities.Polls.FirstOrDefault(p => p.PollID == Id);
}
public IQueryable<Poll> CurrentPoll()
{
return entities.Polls.Where(c => c.IsCurrent == true);
}
public PollOption GetPollOption(int Id)
{
return entities.PollOptions.FirstOrDefault(o => o.OptionID == Id);
}
PollController.cs
public class PollsController : Controller
{
PollRepository pollRepository = new PollRepository();
//
// GET: /Polls/
public ActionResult Index()
{
var polls = pollRepository.GetPolls().ToList();
return View(polls);
}
}
here is my index.cshtml View
#model IEnumerable<PollSystem.Models.Poll>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.Partial("PollItem")
</td>
</tr>
}
and lastly my Particle View
#model PollSystem.Models.Poll
<div id="poll-#Model.PollID" class="poll">
<h2>#Model.QuestionText</h2>
#using (Html.BeginForm(FormMethod.Post))
{
<ul class="poll-options">
#foreach (var option in Model.PollOptions)
{
<li class="option" id="option-#option.OptionID">
<input type="radio" id="option-#option.OptionID" value="#option.OptionID"/>
<label class="text" for="option-#option.OptionID">
#option.OptionText
</label>
</li>
}
</ul>
<button type="submit" name="poll-submit">Vote</button>
}
</div>
If you do not explicitly pass a model to the partial view, it will use the model of the parent view, from which the partial view is called. In your case, you are not passing any model to the partial view method call, hence it is using the model of the parent page which is IEnumerable<PollSystem.Models.Poll> as the model of the partial.
Use this overload of Partial method which takes the model of the partial view as the second parameter
public static MvcHtmlString Partial(
this HtmlHelper htmlHelper,
string partialViewName,
object model
)
So in your main view, you can pass the item variable to the Partial call
#model IEnumerable<PollSystem.Models.Poll>
#foreach (var item in Model) {
<tr>
<td>
#Html.Partial("PollItem",item)
</td>
</tr>
}
Please try
#model IEnumerable<PollSystem.Models.Poll>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.Partial("PollItem",item)
</td>
</tr>
}
I am using VS2012 MVC 4 with EF. I want to make a view where the user can upload movie title and type for it (actionmovie, scifi, etc that comes from a dropdownlist!), and store it in database.
Model:
public class Movie
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Type")]
public int TypeId { get; set; }
public virtual Type Type { get; set; }
}
public class Type
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int TypeId { get; set; }
public string TypeName { get; set; }
public virtual ICollection<Movie> Movies { get; set; }
}
If I am right I successfully made One to Many relationship between the Type and Movie table.
Controller:
[HttpPost]
[Authorize]
public ActionResult NewMovie(Movie movie)
{
db.Movies.Add(movie);
db.SaveChanges();
return View(movie);
}
View:
#using (Html.BeginForm())
{
<table>
<tr>
<td>#Html.DisplayNameFor(model => model.Name)</td>
<td>#Html.DisplayNameFor(model => model.TypeId)</td>
</tr>
<tr>
<td>#Html.TextBoxFor(model => model.Name)</td>
<td>#Html.DropDownListFor.........
</tr>
</table>
<input type="submit" value="submit" />
}
I do not really know how should I make this Dropdownlist in the view, and make the specific details for it in the controller with the most secure way
(I think i should make a list/enumerable from the movie.typeid or the Type class)
I would be very glad if you could help me! Thank you
I use List for my dropdown list. to do it that way you can build the list like this on your controller
List<SelectListItem> ls = new List<SelectListItem>();
foreach(var temp in Movies){
ls.Add(new SelectListItem() { Text = temp.Text, Value = temp.Value });
}
Movie.MovieList = ls;
you can only pass one model to the view. from your code you are passing the movie model so put
public List<SelectListItem> MovieList { get; set; }
in your model. Then on the view you can build your dropdownlist like this
#Html.DropDownListFor(x => x.Id, Model.MovieList)
Let me know if you have any questions.
I'm having problems trying to validate a drop down list, I've looked at similar questions on here and tried the suggestions but still no luck. One I haven't tried is making my Benefit Id nullable, but is that a good idea? many thanks
Model I'm trying to validate:
public class Benefit
{
public int Id { get; set; }
public string Name { get; set; }
}
View model:
public class LookupVm
{
public SelectList Benefits { get; set; }
}
Controller set up:
var model = new LookupVm
{
Benefits = new SelectList(_repository.Benefits.OrderBy(n => n.Name).ToList(), "Id", "Name")
}
The view:
#Html.DropDownListFor(benefits => Model.Benefits.SelectedValue, Model.Benefits, "-Select-")
#Html.ValidationMessageFor(benefits => Model.Benefits.SelectedValue)
You can add a SelectedBenefit property to you view model
public class LookupVm
{
public int SelectedBenefit { get; set;}
public SelectList Benefits { get; set; }
}
Then add on top of the view
#model LookupVm
And then dropdown list must be something like this:
#Html.DropDownListFor(model => model.SelectedBenefit, model.Benefits, "-Select-")
#Html.ValidationMessageFor(model => model.SelectedBenefit)
You will get the selected id on SelectedBenefit property and it will be a required field.