I am using an MVC model and i want to save the selected value from a dropdownlist.
here is what i have so Far
Model.
namespace FormsAuthenticationMVC.Models
{
using System;
using System.Collections.Generic;
public partial class Report_Security
{
public int ID { get; set; }
public Nullable<int> UserName_ID { get; set; }
public string ReportName { get; set; }
public string Report_Url { get; set; }
public string EmbedCode { get; set; }
public List<Report_Security> ReportList { get; set; }
}
}
My Controller
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FormsAuthenticationMVC.Models;
namespace FormsAuthenticationMVC.Controllers
{
//[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Reports()
{
// this is working fine. the dropdown is populated from the model correctly.
ViewBag.Message = "O2 Dashboard";
ASP_AuthEntities ReportTable = new ASP_AuthEntities();
var getReportTable = ReportTable.Report_Security.ToList();
SelectList list = new SelectList(getReportTable, "EmbedCode", "ReportName");
ViewBag.ReportListName = list;
return View();
}
[HttpPost]
public ActionResult Reports(Report_Security model, string Code)
{
if (ModelState.IsValid)
TempData["HtmlSelected"] = Code; // = This is where i shall set the dropdown value
return View(model);
}
}
}
and my view
#model FormsAuthenticationMVC.Models.Report_Security
#{
<h2>#ViewBag.Message</h2>
}
#Html.DropDownListFor(r =>r.EmbedCode, new SelectList(Model.EmbedCode,"EmbedCode"),"Select Report")
<h5>#TempData["HtmlSelected"]</h5> #*----- SELECTED DROPDOWN VALUE*#
When i run debug and i put a breakpoint in my view at the #Html.DropDownListFor ...... line i get the following error.
System.Web.Mvc.WebViewPage.Model.get returned null.
Could someone help me out please.
Related
I've fairly new to Asp.net core MVC and have spent days researching this and I can't find my error.
I'm simply trying to pass data from a ViewModel to a table in a view but the ViewModel isn't populating data.
Here's my code:
The model I'm currently working with (The others look the same with different columns):
using System;
using System.Collections.Generic;
namespace Seating.Models
{
public partial class Dth
{
public int Id { get; set; }
public DateTime TimeEntered { get; set; }
public DateTime? TimeCleared { get; set; }
public bool? EmpSent { get; set; }
public int EmployeeId { get; set; }
public int EmpPosition { get; set; }
public int? RlfPosition { get; set; }
public virtual Position EmpPositionNavigation { get; set; }
public virtual Employee Employee { get; set; }
public virtual Position RlfPositionNavigation { get; set; }
}
}
VM:
using Seating.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Seating.ViewModels
{
public class ListsVM
{
public IEnumerable<Dth> Dths { get; set; }
public IEnumerable<Break> Breaks { get; set; }
public IEnumerable<Lunch> Lunches { get; set; }
public IEnumerable<Employee> Employees { get; set; }
public IEnumerable<Position> Positions { get; set; }
}
}
Controller:
using Seating.Models;
using Seating.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace Seating.Controllers
{
public class HomeController : Controller
{
private readonly db_a7e17a_seatingContext _context = new db_a7e17a_seatingContext();
public HomeController(db_a7e17a_seatingContext context)
{
_context = context;
}
public ActionResult Index()
{
var tables = new ListsVM
{
Employees = _context.Employees.ToList(),
Dths = _context.Dths.Where(n => n.TimeCleared == null).ToList(),
Breaks = _context.Breaks.Where(n => n.TimeCleared == null).ToList(),
Lunches = _context.Lunches.Where(n => n.TimeCleared == null).ToList(),
Positions = _context.Positions.ToList()
};
return View(tables);
}
And view:
#model IEnumerable<Seating.ViewModels.ListsVM>
#{
ViewData["Title"] = "Home Page";
}
<div class="card" style="width: 18rem;">
<div class="card-header text-center">
DTH
</div>
<table class="table table-sm">
<tbody>
#foreach (var item in Model.Dths)
{
<tr>
#item.EmployeeId
</tr>
}
</tbody>
</table>
</div>
I'm getting an error saying 'IEnumerable' does not contain a definition for 'Dths'accepting a first argument of type 'IEnumerable' could be found.
I tried changing "IEnumerable" to "List" in the VM. I've read many solutions on stackoverflow. I've taken tutorials that have showed me how to set things up. As far as I can tell I'm following the tutorial code to the letter, even thought I'm clearly not somewhere.
I changed the model reference in the view to #model IEnumerable<Seating.Models.Dth> instead of the VM. That works perfectly. So I'm assuming I'm doing something wrong with the VM since it works referencing the model directly without going through a VM.
Any thoughts on what I'm doing wrong?
You are creating an object of type ListsVM that contains lists of different kinds of entities. And this object is passing to the view by View(tables). But in the view you declared your model as a collection of objects ListsVM: #model IEnumerable<Seating.ViewModels.ListsVM>
Did you try to change the model declaration to #model Seating.ViewModels.ListsVM?
If to declare the view model as #model Seating.ViewModels.ListsVM then the Model.Dths will be referencing to correct collection and the #foreach (var item in Model.Dths) will enumerate this collection properly.
I have figured out how to make a dropdownlist with static data, but I want to display data from my database. How do I fill my list with data from the model Neighbourhoods? I want to display all the NeighbourhoodNames in my dropdown.
I am using .net core 5.0 with MVC
My cshtml code:
<select asp-for="Neighbourhood" asp-items="Model.NeighbourhoodList"></select>
My Model:
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace MyProject.Models
{
[Keyless]
public partial class Neighbourhoods
{
public string NeighbourhoodGroup { get; set; }
public string NeighbourhoodName { get; set; }
public List<SelectListItem> NeighbourhoodList { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "a", Text = "New York" },
new SelectListItem { Value = "b", Text = "Los Angeles" },
};
}
}
My Controller:
// GET: Neighbourhoods/Create
public IActionResult Create()
{
var vm = new Neighbourhoods();
return View(vm);
}
This might be a dumb question as I'm new to the MVC pattern in asp.net.
I'm trying to access to the value in my database but the values don't get rendered
on the view page.
here's the code I have written.
code for the "Resturant" model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace OdetoFood.Models
{
[Table("Resturants")]
public class Resturant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<ResturantReviews> Reviews { get; set; }
}
}
here's my DbContext model:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace OdetoFood.Models
{
public class OdeToFoodDb : DbContext
{
public DbSet<Resturant> Resturants { get; set; }
public DbSet<ResturantReviews> Reviews { get; set; }
}
}
Code for the controller class:
public class HomeController : Controller
{
OdeToFoodDb _db = new OdeToFoodDb();
public ActionResult Index()
{
var model = _db.Resturants.ToList();
return View(model);
}
and here's the view that should be displaying the values:
#model IEnumerable<OdetoFood.Models.Resturant>
#{
ViewBag.Title = "Home Page";
}
#foreach (var item in Model)
{
<h3>#item.Name</h3>
<div>#item.City, #item.Country</div>
<div>#item.Id</div>
}
the connection string in Web.config is setup like this:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-OdetoFood-20150611025411.mdf;Initial Catalog=aspnet-OdetoFood-20150611025411;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
What am I doing wrong here?
This would be the seed method for that project:
protected override void Seed(OdeToFood.Models.OdeToFoodDb context)
{
context.Restaurants.AddOrUpdate(r => r.Name,
new Restaurant { Name = "Sabatino's", City = "Baltimore", Country = "USA" },
new Restaurant { Name = "Great Lake", City = "Chicago", Country = "USA" },
new Restaurant
{
Name = "Smaka",
City = "Gothenburg",
Country = "Sweden",
Reviews =
new List<RestaurantReview>{
new RestaurantReview{ Rating = 9, Body="Great Food!" }
}
});
}
I'm having a lot of trouble trying to create a partial view on my home controller from a .edmx model.
I cannot change the properties of this model because it is a part of another system that I am building this Website around.
I have spent a very long time trying to work this out and have came here to hopefully get some help and advice.
Aim: Render a partial _Patient.cshtml view on the Homepage using models in an .edmx model. I would like for you to show me where I have gone wrong as it does not work.
What is the problem?
I get multiple errors such as:
model: : EntityType model has no key defined. Define the key for this entity type.
The model item passed into the dictionary is of type 'Models', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`
using the generic type 'system.collections.generic.ienumerable requires 1 type arguments MVC
Currently I'm getting this error but I get the feeling that it's at the front of a long list of them.
The model item passed into the dictionary is of type 'FaceToFaceWebsite.Models.PatientListViewModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[FaceToFaceWebsite.Models.PatientListViewModel]'.
Below is the .edmx
(as I cannot post images yet..
User (edmx)
-Properties-
UserID
CodeName
UseBriefInstructions
Device_DeviceID
-Navigation Properties-
Device
RegimeItems
Device
-Properties-
DeviceID
Name
-Navigation Properties-
Users
Session
-Properties-
SessionID
ActiveUserID
ActiveDeviceID
StartedAt
ReachedFinish
-Navigation Properties-
SessionExcercises
(the Edmx is alot bigger than shown however these are the models that i currently need to use. however session and user are infact linked through another model)
HomeController.cs
using FaceToFaceWebsite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Web;
using System.Web.Mvc;
using PagedList;
using System.Web.UI;
using System.Configuration;
using System.Collections;
namespace FaceToFaceWebsite.Controllers
{
public class HomeController : Controller
{
public F2FDataEntities _db = F2FDataEntities();
[OutputCache(CacheProfile = "Long", VaryByHeader = "X-Requested-With", Location = OutputCacheLocation.Server)]
public ActionResult Index(string searchTerm = null, int page = 1)
//public ActionResult Index()
{
var model =
_db.UserID.ToList()
.OrderByDescending(u =>u.UserID)
.Take(10)
.Select (u => new PatientListViewModel
{
CodeName = u.CodeName,
Name = u.Name
}).ToPagedList(page, 10);
return PartialView("_Patient", new FaceToFaceWebsite.Models.PatientListViewModel());
////return View(model);
////ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Patients()
{
ViewBag.Message = "";
return View();
}
public ActionResult Help()
{
ViewBag.Message = "";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Contact Us";
return View();
}
protected override void Dispose(bool disposing)
{
if (_db != null)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
PatientListViewModel
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data.Entity;
namespace FaceToFaceWebsite.Models
{
public class PatientListViewModel
{
public virtual ICollection<User> CodeName { get; set; }
public virtual ICollection<Session> ReachedFinish { get; set; }
public virtual ICollection<Device> Name { get; set; }
}
}
Views/Home/Index.cshtml
System.Collections.Generic.IEnumerable<FaceToFaceWebsite.Models.PatientHomeViewModel>*#
#{
ViewBag.Title = "Home Page";
}
#Html.Partial("_Patient", Model)
Views/Home/_Patient.cshtml
#model IEnumerable<PatientListViewModel>
#foreach (var item in Model)
{
<div>
<h4>UserID: #item.CodeName</h4>
<span>Finished: #item.ReachedFinish</span>
<p>Machine: #item.Name</p>
<hr />
</div>
}
PatientProfile.cs (i tried making another model to as a different approach but to no success)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace FaceToFaceWebsite.Models
{
public class PatientProfile : DbContext
{
public PatientProfile() : base("F2FDataEntities")
{
}
public DbSet<User> UserID { get; set; }
public DbSet<Device> Name { get; set; }
//public DbSet<RestaurantReview> Reviews { get; set; }
public System.Data.Entity.DbSet<FaceToFaceWebsite.Models.PatientListViewModel> PatientListViewModels { get; set; }
}
}
F2FDataDB.cs(I Tried creating another Db that would use the models from the edmx)
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace FaceToFaceWebsite.Models
{
public class F2FDataEntities : DbContext
{
public F2FDataEntities() : base("name=F2FDataEntities")
{
}
public DbSet<User> UserID { get; set; }
public DbSet<User>CodeName { get; set; }
//public DbSet<Session> SessionDB { get; set; }
public DbSet<Device> Name { get; set; }
public System.Data.Entity.DbSet<FaceToFaceWebsite.Models.PatientListViewModel> PatientListViewModel { get; set; }
}
}
I've posted everything i see as relevant, if you need anymore information please let me know.
I apologise if the solution is simple, im new to MVC and this problem has gone on for quite some time.
---------UPDATE 2.0-------------
Views/home/index.cshtml
#model FaceToFaceWebsite.Models.PatientListViewModel
#{
ViewBag.Title = "Home Page";
}
#Html.Partial("_Patient", Model.PatientProfile)
views/shared/_Patient.cshtml (partial view)
#model List<PatientProfile>
#foreach (var item in Model)
{
<div>
<h4>UserID: #item.CodeName</h4>
<div>
#*<span>UserName: #item.CodeName</span>*#
</div>
#*<span>Started Session at: #item.StartedAt</span>*#
<span>Finished: #item.ReachedFinish</span>
<p>Machine: #item.Name</p>
<hr />
</div>
}
patientlistviewmodel.cs
namespace FaceToFaceWebsite.Models
{
public class PatientListViewModel
{
public List<Patient> PatientProfile { get; set; }
}
public class Patient
{
public int UserID { get; set; }
public string CodeName { get; set; }
}
}
HomeController.cs
namespace FaceToFaceWebsite.Controllers
{
public class HomeController : Controller
{
public F2FDataEntities _db = new F2FDataEntities();
public ActionResult Index()
{
var viewModel = new PatientListViewModel();
viewModel.PatientProfile = new List<Patient>();
return View(viewModel);
}
}
}
Models/PatientProfile.cs
namespace FaceToFaceWebsite.Models
{
public class PatientProfile : DbContext
{
public PatientProfile() : base("F2FDataEntities")
{
}
public DbSet<User> UserID { get; set; }
public DbSet<User> CodeName{ get; set; }
public DbSet<Device> Name { get; set; }
public DbSet<Session> ReachedFinish { get; set; }
}
}
I am currently getting this error:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code
Additional information: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[FaceToFaceWebsite.Models.Patient]', but this dictionary requires a model item of type
I am getting this error at "..#Html.Partial("_patient", Model.PatientProfile)"
_Patient (Partial view)
#model List<PatientProfile>
#foreach (var item in Model)
{
<div>
<h4>UserID: #item.CodeName</h4>
<span>Finished: #item.ReachedFinish</span>
<p>Machine: #item.Name</p>
<hr />
</div>
}
1.
You are passing back the PartialView as a Result:
return PartialView("_Patient", new FaceToFaceWebsite.Models.PatientListViewModel());
Change this to return View(model); In your Index function. This will return your Home Page "Views/Home/Index.cshtml", and in this Index view you have:
#Html.Partial("_Patient", Model)
Which will Render the Partial View. But you are passing the wrong Model to your Index View: in Controller you are passing PatientListViewModelBut in you index you have: IEnumerable<FaceToFaceWebsite.Models.PatientHomeViewModel>.
So either you pass IEnumerable<FaceToFaceWebsite.Models.PatientHomeViewModel>,
like this:
public ActionResult Index(){
return PartialView(new FaceToFaceWebsite.Models.PatientListViewModel());
}
And then you can call Partial View like this:
#model IEnumerable<FaceToFaceWebsite.Models.PatientHomeViewModel>
#{
ViewBag.Title = "Home Page";
}
#Html.Partial("_Patient", Model)
What you should do.
Controller:
public ActionResult Index()
{
var viewModel = PatientListViewModel();
viewModel.PatientList = new List<Patients>();
viewModel.CustomerList = new List<Cusotmer>();
return View(viewModel);
}
Index.cshtml
#model PatientListViewModel
#* Considering your partial view is in Shared Foler*#
// Note Passing the Correct Model to Partial View
#Html.Partial("_Patient", Model.PatientsList)
// Another Example:
#Html.Partial("_Customer", Model.CustomerList)
Your _Patient.cshtml (partial View)
#model List<PatientsList>
#foreach(var item in Model){
item.Name
}
Your _Customer.cshtml (partial View) // Another Example
#model List<Custom>
#foreach(var item in Model){
item.Name
}
Your ViewModel:
public class PatientListViewModel{
public List<Patient> PatientsList {get;set;}
public List<Customer> CustomerList{get;set;}
}
public class Patient{
public string Name {get;set;
}
// Another Example
public Class Customer{
public string Name{get;set;
}
UPDATE
#model FaceToFaceWebsite.Models.PatientListViewModel
#{
ViewBag.Title = "Home Page";
}
// PatientListViewModel this is the Name of you class
// To Access your Model you always have to use Model. Not the Class Name
// PatientListViewModel is the Class name
// Model is the Object --> You passed from Controller.
// Use Model.PatientProfile
// Not PatientListViewModel.PatientProfile
#Html.Partial("_Patient", Model.PatientProfile)
I always get the error-- cannot convert to 'MvcMusicStore.Models.MusicStore.GenreDataTable' to 'System.Collections.Generic.IEnumerable'
I am pasting my code below
the controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMusicStore.Models;
namespace MvcMusicStore.Controllers
{
public class StoreController : Controller
{
// GET: /Store/
public ActionResult Index()
{
MvcMusicStore.Models.MusicStoreTableAdapters.GenreTableAdapter ta= new Models.MusicStoreTableAdapters.GenreTableAdapter();
var genres = ta.GetData().AsEnumerable();
return View(genres);
}
my model:
namespace MvcMusicStore.Models
{
public partial class Genre
{
public int GenreId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Album> Albums { get; set; }
}
}
and at last the view:
#model IEnumerable<MvcMusicStore.Models.Genre>
#{
ViewBag.Title = "Index";
}
<h3>Browse Genres</h3>
<p>
Select from #Model.Count()
genres:
</p>
<ul>
#foreach (var genre in Model)
{
<li>#Html.ActionLink(genre.Name,
"Browse", new { genre = genre.Name })</li>
}
</ul>
It looks like ta.GetData() is not returning an object that can be cast into an IEnumerable<Genre>. Based on the error message it seems that ta.GetData() is returning a GenreDataTable object. If that is correct, I see a couple of things:
In the Razor view, the model is looking for a IEnumerable of Genre objects not a GenreDataTable object.
If your GenreDataTable object is already a collection, then have that as the return model instead of the IEnumerable.
If GenreDataTable is not a collection of Genre objects, then you've got to either update the required model in the Razor view, or update the controller code to create the required type to match the model.