how model use for display two tables in a view - c#

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

Related

Generate a list of contacts from a table based on a Bool value

I am currently developing an asp.NET MVC web application as a front end to a database. I have a MySQL database, one of the tables is contact information for employees. I have added a column of 'isOnSite' of datatype TINYINT(1).
I have updated the data model in my application, and added a checkbox control for this in one of my view. This works fine, I edit a contact, check the box to say that they are currently contracted to this particular site, and a '1' is populated in the 'isOnSite' column for that particular record, great!
One of the views is a Dashboard. In this view (using a partial view) I would like to generate a list of the contacts in the table that have the value of 'isOnSite = true'
I am struggling to do this. I should mention that I am pretty new to all of this.
Any help would be greatly appreciated.
Thank you in advance!
-- EDIT --
With the help of #Bunnynut and also my Father-in-Law We managed to solve this,
in large part to the code examples by #Bunnynut.
CONTROLLER ACTION
public ViewResult Index()
{
var tblcontacts = from m in db.tblcontacts.Where(x => x.isOnSite)
select m;
return View(tblcontacts.OrderBy(x => x.LastName).ToList());
}
PARTIAL VIEW
#model IEnumerable<ResourceBase.Models.tblcontact>
#{
ViewBag.Title = "OnSite";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>OnSite</h2>
<div class="container-fluid-viewport jumbotron col-xs-offset-4">
#foreach (var x in Model)
{
#x.FullName <br />
}
</div>
And the Main view just renders the partial view.
Thanks again for your help #Bunnynut
To begin with the Index View uses a model of type ResourceBase.Models.tlbcontact which is it seems a single tblcontcat.
But you are try to pass a List to your partial view so that is not possible.
You Index View should consume a model of which it pass parts of it to your partial views.
IndexViewModel:
public class IndexViewModel
{
public string Title { get; set; }
public List<ResourceBase.Models.tblcontact> Employees { get; set; }
}
Index Action:
public ActionResult Index()
{
var model =
new IndexViewModel
{
Title = "PeopleBase Dashboard",
Employees = GetEmployees()
};
return View(model);
}
Index View:
#model IndexViewModel
<div class="container-fluid-viewport col-md-offset-3 col-md-9">
<h2>#Model.Title</h2>
<div class="partialViewWrapper jumbotron">#{Html.RenderPartial("_peopleBaseDashView", Model.Employees.Where(x => x.isOnSite).ToList());}
</div>
</div>
Your partial View looks ok to me
Use the following SELECT statement
SELECT * FROM yourTable WHERE isOnSite = 1
to fill a property of your ViewModel, which you can then display in your view.
You can easily pass the list of employees directly to your partial view as long as you tell your partial view the model passed is of that type.
So in the master view containing the code that call the partial view you can do this:
#{Html.RenderPartial("NAME_PARTIAL_VIEW", employees.Where(x => x.isOnSite).ToList());}
And in you partial view:
#model List<Employee>
#foreach(var employee in Model)
{
#employee.Name
}

Mvc controller to view from sql Ienumerable problem

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>

Dropdownlists not populating with data from 3 separate reference tables

Currently I am working with ASP.Net MVC 6 using EF7. I am using the default controller generator. For some reason my drop downs are not populating with data on the create or edit page even though data is present.
Just to clarify the 3 select lists are being populated by 3 different tables that are all connected to the main table I am adding to.
Here's what I got.
Controller code
private readonly SchoolContext _context;
public SchoolsController(SchoolContext context)
{
_context = context;
}
public IActionResult Create()
{
ViewData["DistrictId"] = new SelectList(_context.Districts, "DistrictId", "District");
ViewData["LocationId"] = new SelectList(_context.Locations, "LocationId", "Location");
ViewData["TierId"] = new SelectList(_context.Tiers, "TierId", "Tier");
return View();
}
View code
#model School
is included at the top and here is what one of the select element looks like
<div class="form-group">
<label asp-for="DistrictId" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="DistrictId" class ="form-control"></select>
</div>
</div>
The select lists are completely blank with no errors there is data.
This is all generated automatically so I am totally clueless on what went wrong. Any suggestions?
You need both a property to bind to (the selected value) and a property for the options and they need to have different names. Ideally you should be using a view model which would have (say)
public class SchoolVM
{
public int DistrictId { get; set; }
public IEnumerable<SelectListItem> DistrictList { get; set; }
....
and in the GET method
public IActionResult Create()
{
SchoolVM model = new SchoolVM
{
DistrictList = new SelectList(_context.Districts, "DistrictId", "District"),
.....
};
return View(model);
}
and in the view
#model SchoolVM
....
<select asp-for="DistrictId" asp-items="Model.DistrictList"></select>
alternatively, you could use ViewBag or ViewData and use
<select asp-for="DistrictId" asp-items="ViewBag.DistrictList"></select>
Assuming your view name is School (the convention for ViewModel is name of the view + "ViewModel")
class SchoolViewModel
{
IEnumerable<SelectListItem> Districts;
IEnumerable<SelectListItem> Locations;
IEnumerable<SelectListItem> Tiers;
}
Then in your view,
#model SchoolViewModel
...
#Html.DropDownList("Districts", m=>m.Districts, "-- Select--")
#Html.DropDownList("Locations", m=>m.Locations, "-- Select--")
#Html.DropDownList("Tiers", m=>m.Tiers, "-- Select--")
In your controller
public IActionResult Create()
{
var vm = new SchoolViewModel();
vm.Districts = _context.Districts.Select(d => new
{
Text = d.District,
Value = d.DistrictId.ToString()
};
//repeat for others...
return View(vm);
}

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();

NullReference error on foreach used to create radiobuttons on POST

I am teaching myself asp .net mvc3. I have a "add property" form which allows user to upload property details to the website. I have been struggling with this error for a long time now.
For simplification, lets consider that I have two tables in my database.
CustomerTypes: The database has 1 Owner, 2 Broker, 3 Commercial etc
Property: This is the table that gets populated by the form.
I use CustomerTypes (and other such tables) to create radio buttons. The user fills the form and selects a choice for "customer type". However, I get an "object reference not set to an instance of an object" error on submit. This is is because "null" is
set for Model.CustomerTypes. However, Model.CustomerTypes is only used to create radio buttons. I am not sure what is wrong. The code is below:
View:
#model Website.ViewModels.AddPropertyViewModel
<fieldset>
<legend>Property</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Property.CustomerType)
#foreach (var item in Model.CustomerTypes)
{
#Html.RadioButtonFor(model => model.Property.CustomerType, Convert.ToInt32(item.Value)) #item.Text
}
</div>
...
AddPropertyViewModel:
namespace Website.ViewModels
{
public class AddPropertyViewModel
{
public Property Property { get; set; }
...
public IEnumerable<SelectListItem> CustomerTypes { get; set; }
...
}
Controller:
public ActionResult AddProperty()
{
AddPropertyViewModel viewModel = new AddPropertyViewModel
{
...
CustomerTypes = websiterepository.GetCustomerTypeSelectList(),
...
};
return View(viewModel);
GetCustomerTypeSelectList functions is:
public IEnumerable<SelectListItem> GetCustomerTypeSelectList()
{
var customerTypes = from p in db.CustomerType
orderby p.CustomerTypeDescription
select new SelectListItem
{
Text = p.CustomerTypeDescription,
Value = SqlFunctions.StringConvert((double)p.CustomerTypeId)
};
return customerTypes;
}
The value in POST is set for Property_CustomerType correctly based on the selection
--- Added further info ---
I start the form as:
#using (Html.BeginForm("AddProperty", "Property", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
}
The controller is:
[HttpPost]
public ActionResult AddProperty(AddPropertyViewModel viewModel)
{
if (ModelState.IsValid)
{
//
if (viewModel.File1.ContentLength > 0)
{
var fileName = Path.GetFileName(viewModel.File1.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
viewModel.File1.SaveAs(path);
}
var property = viewModel.Property;
websiterepository.Add(property);
return RedirectToAction("Index", "Home");
}
return View(viewModel);
}
Here is a screenshot of error:
I have tried submitting the form commenting these radio buttons and it works.
The issue is that CustomerTypes isn't populated when your render the view after posting to the server.
If we look at the flow of actions being performed we see that
You populate the CustomerTypes collection before rendering the
inital page
You post your data back to the server but do not
preserve the CustomerTypes collection (Because there's no need to)
You render the view again but this time without populating
CustomerTypes.
Kaboom!
Populating the CustomerTypes property before you return the view for the second time should fix your problem:
[HttpPost]
public ActionResult AddProperty(AddPropertyViewModel viewModel)
{
[...]
viewModel.CustomerTypes = websiterepository.GetCustomerTypeSelectList();
return View(viewModel);
}

Categories

Resources