Mvc controller to view from sql Ienumerable problem - c#

I'm trying to get all the info (column, rows) from a table in SQL and send it as a model to the view.
I also want it to be Distinct.
My controller:
MVCEntities me = new MVCEntities();
List<CarsCategory> arr = me.CarsCategories.ToList();
return View(arr);
My view model:
#model IEnumerable<CarsCategory>
In the view I'm trying to loop through a certain column like this:
<select id="SelectManufacturer">
#foreach (var i in Model)
{
<option value="#i.Manufacturer">#i.Manufacturer</option>
}
</select>
How do I make it Distinct? When I try to add Distinct it gives me system.linq.enumerable+<DistinctIterator> ..

Although it's not a good approach to process data inside the view, your solution might look like this:
<select id="SelectManufacturer">
#{
var manufacturers = Model.Select(x => x.Manufacturer).Distinct().ToList();
foreach (var i in manufacturers)
{
<option value="#i">#i</option>
}
}
</select>

The controller should be responsible to supply the View with the data, the view should not be polutted with a bunch of logic to try to aggregate this data unless you want unmaintainable code. The best approach is to extend your view model to have multiple properties.
Models
public class CategoryModel{
public List<CarsCategory> CarCategories {get;set;}
public List<Manufacturer> Manufacturers {get;set;}
}
public class Manufacturer{
public int Id {get;set;}
public string Name {get;set;}
}
Controller code
// you need to ensure that if you are using EF the context is disposed after you are done using it!
using(MVCEntities me = new MVCEntities()) {
var model = new CategoryModel();
model.CarCategories = me.CarsCategories.ToList();
// you need to supply the correct Id and Name locations in your model as you did not share this
model.Manufacturers = model.CarCategories.Select(x => new Manufacturer(){Id = x.prop.id, Name = x.prop.name}).Distinct();
return View(model);
}
Razor View
#model CategoryModel
<select id="SelectManufacturer">
#foreach (var i in Model.Manufacturers)
{
<option value="#i.Id">#i.Name</option>
}
</select>

Related

Causing problems with foreach into my mvc

This is how I have made a previous post as you can see here.
must retrieve the list from the database
I have tried to make my foreach which have been previously described. but it causes problems for not running my foreach in through while making the mistake on it.
Index.cshtml
#foreach (var u in Model)
{
<div class="col-md-6 col-sm-6">
<div class="plan">
<h3>#u.Name<span>$#u.Price</span></h3>
<p>#u.Text</p>
</div>
</div>
}
and undervisningController.cs
// GET: Undervisning
public ActionResult Index()
{
DatabaseClasseDataContext db = new DatabaseClasseDataContext();
var model = db.Packages.ToList();
return View(model);
}
And the top on index.cshtml have i:
#model MentorOrdblind_MVC.Models.Undervisning.Undervisning
Model Undervisning.cs
public class Undervisning
{
public string Name { get; set; }
public decimal Price { get; set; }
public int Hours { get; set; }
public string Text { get; set; }
}
You are passing your view a List<T> but your model is not a type of IEnumerable. So your view is only expecting a single object of the type Undervisning and not a collection.
Use this:
#model IEnumerable<MentorOrdblind_MVC.Models.Undervisning.Undervisning>
Change your model delcaration to:
#model IEnumerable<MentorOrdblind_MVC.Models.Undervisning.Undervisning>
At this moment your model is a single class, not a list of objects
Always keep in mind what is being passed from controller action to view. If you pass only model from the action then use the model reference in the respective view of the action. If you pass List then use IEnumerable model reference in the view.
If you pass list from action then in the view use:
#model IEnumerable<your model> in the top as reference
If you pass model without a list then use:
#model your model
In your case you are passing list so use IEnumerable of your desired model class.
Thanks

Making multiple models cast an ID using Entity Framework

I am new to using the Entity Framework. I have added my Model, and I need to use two my models/tables in one View Page. So to do that I added this to my AccountViewModels.cs page:
public class category_menuitem
{
public Category Category { get; set; }
public MenuItem MenuItem { get; set; }
}
I am trying to use Values from those two Models/Tables.
My View Page:
using System.Data.SqlClient
#model IEnumerable<YourGoGetterV1.Models.category_menuitem>
#{
ViewBag.Title = "Show Menu" - ViewBag.restaurant_id;
}
<h2>ShowMenu</h2>
<div class="jumbotron">
#foreach (var item in Model)
{
<div><strong>#Html.DisplayFor(item1 => item.Category.Name)</strong>
<div>#Html.DisplayFor(item1 => item.Category.Description)</div>
#{
using (var context = new YourGoGetterContext())
{
SqlParameter sa = new SqlParameter("#p0", ViewBag.restaurant_id);
var menu_items = context.MenuItems.SqlQuery("Select * FROM MenuItems where restaurant_id = #p0", sa).ToList();
var test = "DID IT WORK??";
}
}
</div>
}
</div>
Controller:
public ActionResult ShowMenu(string id, int restaurant_id)
{
ViewBag.Id = id;
ViewBag.restaurant_id = restaurant_id;
return View(Models.category_menuitem.ToList((object(id)));
}
I want to cast the ID, so that it creates a different URL for something that passes in a different ID. But I'm having two problems.
1) I can't even put in the Models.Category_menuitem.ToList() because "No overload for method 'ToList' takes 1 arguments"
2)The Models.Category_menuitem does not contain a definition for ToList.
What do I do?
I think you should do it different. The model should contain the data you use in the view. So do your db requests in the model and give the model to the view to display the data in it. Don't do SQL requests in the view. You also should write classnames always in capital letters because of C# naming conventions.
If I understand it right you want to display a menubar or something like that with categories and each category has many menuitems?
Just create a model menuitems like this:
public class MenuItems {
public List<Category> Categories{get;set;}
}
and a model Category like this:
public class Category {
public string CategoryName {get;set;}
public List<MenuItem> MenuItems {get;set;}
}
Fill the models with data and give the MenuItems Model to the view. In the view you can do something like:
#foreach (var category in Model.Categories)
{
foreach (var menuItem in category.MenuItems)
{
}
}
I hope this helps ;)
To this part of your code:
var menu_items = context.MenuItems.SqlQuery("Select * FROM MenuItems where restaurant_id = #p0", sa).ToList();
I am not sure what you wanna do. You are querying the db for data which should be already in the model or am I wrong? But if you want to use EF you would write:
var items = context.Menuitems.Where(m => m.restaurant_id == id).ToList();

how model use for display two tables in a view

I want to display elements of two tables in a view but I don't know how.
In my view i Have #model IEnumerable which point to 'Tmembre' class of the model and corresponding of the table 'Tmembre' in database.
I can display elements of this table in my view, OK.
but I also want to display elements of another table in the this view and I can't put other #model déclaration in the view.
I try to create a class in the model for two table and put the sql in the model but i think it s not in the model i have to request DB.
public class myviewmodel
{
public Tmembre tmembre { get; set; }
public List<Tmembre> GetlstMembre { // SQL }
public TAssociation tassociation { get; set; }
public List<TAssociation> GetlstAssociation { // SQL }
}
In your controller you can create a new instance of the above ViewModel and fill the members with data from your database.
Once done you should return this ViewModel to your View;
public ActionResult Index()
{
MyViewModel myViewModel = new MyViewModel();
myViewModel.lstmembre = ....;
myViewModel.1stassociation = ...;
return View(myViewModel);
}
In your view you can now specify the #model as your view model
#model myproject.web.models.MyViewModel
Now all members of this model should be available for you to access from your view
Model.1stmembre
Model.1stassociation
Model.tmembre
etc..
OK
ViewBag.Message = "Liste des membres";
//Chercher les informations du membre connecté
//Tmembre Membre = db.TmembresansEDMdb.Find(10);
//TAssociation association = db.dbTassociation.Find(Membre.Idassociation);
//ViewData.Model = (from a in db.TmembresansEDMdb
// where a.Idassociation == Membre.Idassociation
// select a );
myviewmodel mymodel = new myviewmodel();
Tmembre Membre = db.TmembresansEDMdb.Find(1);
mymodel.lstassociation = db.dbTassociation.ToList();
ViewData["Idassociation"] = Membre.Idassociation;
mymodel.lstmembre= (from a in db.TmembresansEDMdb
where a.Idassociation == Membre.Idassociation
select a ).ToList();
return View(mymodel);
In View
#foreach (var item in Model.lstassociation)
{
if (item.Nomassociation == #ViewData["Idassociation"])
{
<option selected>#item.Nomassociation</option>
} else {
<option>#item.Nomassociation</option>
}
}
#foreach (var item in Model.lstmembre) {
<div class="divmembre">
<div class="dphoto"><img src="~/Content/#item.SRCImage"/></div>
<div class="containerdetail">
<div class="ddetail">
<div class="ddetaild nom">#item.Nommembre</div>
<div class="ddetaild prenom">#item.Prenommembre</div>
<div class="ddetaild mail">#item.Mailmembre</div>
</div>
</div>
</div>
}
All elements of lstmembre are displayed but I want to select in a list the element of table Association corresponding with Idassociation in the view data. I have message : no entry point in
if (item.Nomassociation == ViewData["Idassociation"])
but if I use #ViewData["Idassociation"] in HTML Tag and not in a loop it s ok, the value is displayed. I think it s just a syntax error. tks

Grouped data model and nested foreach loops

I'm working on my first complex MVC project. I have an existing database that I used Entity Framework 4.0 to model. The project is basically a survey tool. There are 8 tables in my viewmodel each with a few properties needed in my main survey view. Those are basically questionaire, section, question, and possible answers (to be in the form of dropdownlists) plus the intermediate connecting tables.
public class MyQuestionModel
{
public Questionaire Questionaire { get; set; }
public QuestionaireSection QuestionaireSection { get; set; }
public Section Section { get; set; }
public SectionQuestion SectionQuestion { get; set; }
public Question Question { get; set; }
public QuestionType QuestionType { get; set; }
public QuestionAnswerListCode QuestionAnswerListCode { get; set; }
public AnswerListCode AnswerListCode { get; set; }
}
My ViewMode MyQuestionModel is loaded like this:
public ActionResult Index()
{
var viewModel =
from qa in db.Questionaires
join qas in db.QuestionaireSections on qa.QuestionaireKey equals qas.QuestionaireKey
join s in db.Sections on qas.SectionKey equals s.SectionKey
join sq in db.SectionQuestions on s.SectionKey equals sq.SectionKey
join q in db.Questions on sq.QuestionKey equals q.QuestionKey
join qtc in db.QuestionTypes on q.QuestionTypeKey equals qtc.QuestionTypeKey
join qddl in db.QuestionAnswerListCodes on q.QuestionKey equals qddl.QuestionKey
join ddl in db.AnswerListCodes on qddl.AnswerListCodeKey equals ddl.AnswerListCodeKey
where qa.QuestionaireName.Equals("TAD")
select new MyQuestionModel
{
Questionaire = qa,
QuestionaireSection = qas,
Section = s,
SectionQuestion = sq,
Question = q,
QuestionType = qtc,
QuestionAnswerListCode = qddl,
AnswerListCode = ddl
};
return View(viewModel);
//var viewModel = new List<MyQuestionModel>();
//return View(viewModel);
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<MyQuestionModel> model)
{
if (ModelState.IsValid )
{
// PROCESS THE POSTED DATA HERE
return RedirectToAction("Index", "MyQuestion");
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "error message");
return View(model);
}
When constructing the view by iterating through the results using nested foreach and GroupBy and OrderBy Linq statements doesn't leave me with a model with results I can post back to the controller. I tried using for loops instead of foreach but the grouping issues are causing me problems. If I try loading the ViewModel discretely with out grouping and with just the distinct data for each table I end up with problems getting the correct types for each table and the composite ViewModel. I would guess one of these 3 ways is workable but I'm not sure which way to hang my hat and grind through getting it to work. I'm getting what I need (See Image) in the view using the nested foreach loops but I think I am breaking the model in the process as when I look at the posted model in the controller it is null. Maybe my foreach statements are not constructed properly. I can't help but think there is a more elagent way of doing this. Ultimately I think using editor templates of other partial views may be best but I need to get a prototype working I can refine later.
#model IEnumerable<eValuate_Prototype_07.Models.MyQuestionModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<table>
#foreach (var group in (Model.OrderBy(x => x.QuestionaireSection.DefaultSequence).GroupBy(item => item.Section.SectionName)))
{
<tr>
<th colspan="3">#group.Key</th>
</tr>
foreach (var item in group.OrderBy(x => x.SectionQuestion.DefaultSequence).GroupBy(subItem => subItem.Question.Question1).Distinct()) {
<tr>
<td> </td>
<td>#item.Key</td>
<td>
<select id="ddlAnswerListCode">
<option value="#Guid.Empty"></option>
#foreach (var ans in item.OrderBy(x => x.QuestionAnswerListCode.DefaultSequence))
{
<option value="#ans.AnswerListCode.AnswerListCodeKey">#ans.AnswerListCode.AnswerListCodeName</option>
}
</select>
</td>
</tr>
}
}
</table>
<p>
<input type="submit" value="Save" />
</p>
}
My Questions:
Which is preferred foreach, for loop, or loading the view model discretely then use foreach?
Is the way I'm using foreach breaking my model for posting?

Creating dynamic controls for project

I want to create dymanic controls in my ASP.NET MVC Project.
For example
My Model contains an IList<Product> Products. Every product in this list contains a new IList<ProductItem>.
Product item has properties Text and Value.
Now i want to create one DropDownList for every Products and every dropdownlist should contains items for ProductItem.
Is this possible with HtmlHelpers?
This is pretty straight forward.
In your controller
public ActionResult Index()
{
List<Product> model = GetProductList();
View(model);
}
In your View:
#model IList<Products>
... and then later on ...
#Html.DropDownListFor(item => item.Name, new SelectList(Model, "Name", "Value"))
If you don't want to use helpers, you can always do something like this:
<select>
#foreach (var x in Model)
{
<option value="#x.Value">#x.Text</option>
}
</select>

Categories

Resources