I have an ASP.NET MVC app and I am using Entity framework.
I have a model named Propiedad and this have some virtual properties without Required attibute, in the view I have a dropdown for the virtual properties and when I do not select an option this tell me that I have to select an option.
I need that Grupo property does not need to select another option, that I can select the optionLabel without show me validator error message.
This is the model:
public class Propiedad
{
[Key]
public int Id { get; set; }
public virtual Entidad Entidad { get; set; }
public virtual PestanasPorEntidad Pestana { get; set; }
public virtual GrupoDePropiedades Grupo { get; set; }
public string Codigo { get; set; }
public string Nombre { get; set; }
public string TipoDeDatos { get; set; }
public bool Requerido { get; set; }
[Required]
public int Orden { get; set; }
public string Columna { get; set; }
}
This is part of the view (Create):
<div class="form-group">
#Html.LabelFor(model => model.Grupo, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Grupo.Id, (SelectList)(ViewBag.PestanaList), "Ninguno", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Grupo)
</div>
</div>
This is part of the controller
private void SetGrupoListViewBag()
{
ViewBag.GrupoList = new SelectList(unitOfWork.GrupoDePropiedadesRepository.Get(), "id", "nombre");
}
// GET: /GlobalAdmin/Propiedades/Create
public ActionResult Create()
{
var propiedad = new Propiedad();
SetTipoDeDatosListViewBag();
SetEntidadListViewBag();
SetPestanaListViewBag();
SetColumnaListViewBag();
SetGrupoListViewBag();
var entidadId = Request["entidadId"] != null ? Convert.ToInt32(Request["entidadId"]) : -1;
if (entidadId != -1)
{
propiedad.Entidad = unitOfWork.EntidadRepository.GetById(entidadId);
return View(propiedad);
}
else
{
return View();
}
}
Related
I have this code inside my form:
<div class="form-group">
#Html.LabelFor(c => c.ClosingHourId)
#Html.DropDownListFor(c => c.ClosingHourId, new SelectList(Model.ClosingHours, "Id", "Time"), "Select time", new { #class = "form-control" })
#Html.ValidationMessageFor(c => c.ClosingHourId)
</div>
The "Time" property is of type DateTime, so when I click the dropdown list on my page I see full dates and times, but the thing is I want to display only the hours, without the dates, so I want to use something like Time.ToString("H:mm") but I don't know where can I write this so it will work. Maybe the right approach would be to add something like [Display(Name = Time.ToString("H:mm"))] annotation in my ClosingHour Model? I'm not sure if it's possible.
My View Model:
public class CinemaFormViewModel
{
public int? Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
public string Address { get; set; }
[Required]
[Display(Name = "Total Seats")]
public int TotalSeats { get; set; }
public IEnumerable<OpeningHour> OpeningHours { get; set; }
[Required]
[Display(Name = "Opens At")]
public byte? OpeningHourId { get; set; }
public IEnumerable<ClosingHour> ClosingHours { get; set; }
[Required]
[Display(Name = "Closes At")]
public byte? ClosingHourId { get; set; }
}
My ClosingHour Model:
public class ClosingHour
{
public byte Id { get; set; }
[Required]
public DateTime Time { get; set; }
}
The Action inside the controller which calls the view:
public ActionResult New()
{
var openingHours = _context.OpeningHours.ToList();
var closingHours= _context.ClosingHours.ToList();
var viewModel = new CinemaFormViewModel
{
OpeningHours = openingHours,
ClosingHours = closingHours
};
return View("CinemaForm", viewModel);
}
change you by adding string time property
public class ClosingHour
{
public byte Id { get; set; }
[Required]
public DateTime Time { get; set; }
[NotMapped]
public string ShortTime { get; set; }
}
action
public ActionResult New()
{
var closingHours= _context.ClosingHours.ToList();
var openingHours = _context.OpeningHours.ToList();
closingHours.ForEach(i=> i.ShortTime=i.Time.ToShortTimeString());
openingHours.ForEach(i=> i.ShortTime=i.Time.ToShortTimeString());
// or you can try
closingHours.ForEach(i=> {
i.ShortTime=i.Time.ToShortTimeString();
i.Time=null;
});
openingHours.ForEach(i=> {
i.ShortTime=i.Time.ToShortTimeString();
i.Time=null;
});
var viewModel = new CinemaFormViewModel
{
OpeningHours = openingHours,
ClosingHours = closingHours
};
return View("CinemaForm", viewModel);
}
view
....
#Html.DropDownListFor(c => c.ClosingHourId,
new SelectList(Model.ClosingHours, "Id", "ShortTime"), "Select time", new { #class = "form-control" })
.....
I'm working on an ASP.NET MVC project. I have created the various models and the viewmodels to use in my project. I have also seeded my database table with seed data but upon implementing the registration view, I tested the form but was getting 0 as the value inserted into the Id portion of the database table. I truncated the tables and did a fresh new insert I still had same error.
Below is the model for the user table
public class User
{
[Key]
public byte Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string RefIndicator { get; set; }
public Team TeamCategory { get; set; }
public byte TeamId { get; set; }
public bool IsRegistered { get; set; }
public DateTime DateRegistered { get; set; }
public DateTime? LastModified { get; set; }
public UserRoles UserRoles { get; set; }
public byte UserRolesId { get; set; }
}
and below is the viewModel I created for the Team Model property I needed to use in my view
public class RegisterFormViewModel
{
public User Users { get; set; }
public byte Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public IEnumerable<Team> Teams { get; set; }
public byte TeamId { get; set; }
public string RefIndicator { get; set; }
public bool IsRegistered { get; set; }
public DateTime DateRegistered { get; set; }
public byte UserRolesId { get; set; }
}
And here is the register action to the userController to initialize the values for the Register view
public ActionResult Register()
{
var AppUser = User.Identity.Name.Substring(5);
var AppUserEmail = AppUser + "#nlng.com";
int index = AppUser.IndexOf('.');
var FirstName = AppUser.Substring(0, index);
var LastName = AppUser.Substring(index + 1);
var IsRegistered = true;
var UserRolesId = 1;
var DateRegistered = HttpContext.Timestamp;
var teams = _context.Team.ToList();
var viewModel = new RegisterFormViewModel{
Email = AppUserEmail,
FirstName = FirstName,
LastName = LastName,
Teams = _context.Team.ToList(),
IsRegistered = IsRegistered,
UserRolesId = (byte)UserRolesId,
DateRegistered = DateRegistered
};
return View("Register", viewModel);
}
And finally here is the associated view for the registration page
#model eLeave.ViewModel.RegisterFormViewModel
#{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>User Registration</h2>
#using (Html.BeginForm("Save", "User"))
{
<div class="form-group">
#Html.LabelFor(r=>r.FirstName)
#Html.TextBoxFor(r => r.FirstName, new { #class = "form-control", #readonly = true })
</div>
<div class="form-group">
#Html.LabelFor(r => r.LastName)
#Html.TextBoxFor(r => r.LastName, new { #class = "form-control", #readonly = true })
</div>
<div class="form-group">
#Html.LabelFor(r => r.Email)
#Html.TextBoxFor(r => r.Email, new { #class = "form-control", #readonly = true })
</div>
<div class="form-group">
#Html.LabelFor(r => r.TeamId)
#Html.DropDownListFor(r => r.TeamId, new SelectList(Model.Teams, "Id", "TeamName"), "Select your Team", new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(r => r.RefIndicator)
#Html.TextBoxFor(r => r.RefIndicator, new { #class = "form-control" })
</div>
#Html.HiddenFor(m => m.IsRegistered)
#Html.HiddenFor(m => m.DateRegistered)
#Html.HiddenFor(m => m.UserRolesId)
#Html.HiddenFor(m => m.Id)
#Html.AntiForgeryToken()
<button class="btn btn-primary">Register</button>
}
Finally here's the save action of the userController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(User user)
{
if (!ModelState.IsValid)
{
var viewModel = new RegisterFormViewModel
{
Users = user,
Teams = _context.Team.ToList()
};
return View("Register", viewModel);
}
if (user.Id == 0)
{
_context.User.Add(user);
}
else
{
var usersInDb = _context.User.Single(m => m.Id == user.Id);
usersInDb.FirstName = user.FirstName;
usersInDb.LastName = user.LastName;
usersInDb.TeamCategory = user.TeamCategory;
usersInDb.RefIndicator = user.RefIndicator;
usersInDb.UserRoles = user.UserRoles;
usersInDb.IsRegistered = user.IsRegistered;
usersInDb.Email = user.Email;
usersInDb.DateRegistered = user.DateRegistered;
}
_context.SaveChanges();
return RedirectToAction("Index", "User");
}
The Save Action basically does two things...It saves a new form and it's also used for updating data.
Would appreciate if the bugs in my code can be fished out.
Form what I understand, you need to make ID as auto incremented value.
public class User
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string RefIndicator { get; set; }
public Team TeamCategory { get; set; }
public byte TeamId { get; set; }
public bool IsRegistered { get; set; }
public DateTime DateRegistered { get; set; }
public DateTime? LastModified { get; set; }
public UserRoles UserRoles { get; set; }
public byte UserRolesId { get; set; }
}
I don't think it will work with byte, but you can use int for sure.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(a => a.Id).HasKey(b => b.Id);
modelBuilder.Entity<User>().Property(a => a.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
Testing a Website. While logged in as an admin, the user should be able to delete a Service. A Service could have sub categories known as "Service Options" and below that "Service Option Items". When an admin tries to permanently delete a service he/she receives the following server error.
Server Error
I have done some research and found out that the sub categories may need to be deleted first, and I believe the code reflects that.
Controller
//
// GET: /Service/Delete
[Authorize(Roles = "admin")]
public ActionResult Delete(int id)
{
Service serviceToDelete = db.Services.Where(s => s.ServiceId == id).Single();
return View(serviceToDelete);
}
//
// POST: /Service/Delete
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirm(int id)
{
var serviceToDelete = db.Services.Where(s => s.ServiceId == id).Single();
// remove the service option items
var serviceOptionItems = db.ServiceOptionItems.Where(soi => soi.ServiceOption.ServiceId == serviceToDelete.ServiceId);
foreach (var serviceOptionItem in serviceOptionItems)
{
db.ServiceOptionItems.Remove(serviceOptionItem);
}
// remove the service options
var serviceOptions = db.ServiceOptions.Where(so => so.ServiceId == serviceToDelete.ServiceId);
foreach (var serviceOption in serviceOptions)
{
db.ServiceOptions.Remove(serviceOption);
}
// remove the service
db.Services.Remove(serviceToDelete);
// save all changes
db.SaveChanges();
return RedirectToAction("Index", new { manage = "yes", mode = "all" });
}
View
#model YardLad.Models.Domain.Service
#{
ViewBag.Title = "Delete Service";
}
<script>
$(document).ready(function () {
var isConfirmed = false;
$("form").submit(function (e) {
if (!isConfirmed)
{
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Yes": function () {
$(this).dialog("close");
isConfirmed = true;
$("#deleteService").submit();
},
Cancel: function () {
$(this).dialog("close");
}
}
});
e.preventDefault();
return false;
}
else
{
return true;
}
});
});
</script>
<h2>Delete</h2>
<h3>Are you sure you want to delete this service?</h3>
<div class="display-label">Service Category</div>
<div class="display-field">
#Html.DisplayFor(m => m.ServiceCategory.Name)
</div>
<div class="display-label">Name</div>
<div class="display-field">
#Html.DisplayFor(m => m.Name)
</div>
<div class="display-label">Description</div>
<div class="display-field">
#if (Model.Description == null)
{
#:No Description
}
else
{
#Html.DisplayFor(m => m.Description)
}
</div>
<div class="display-label">Base Price</div>
<div class="display-field">
#Html.DisplayFor(m => m.BasePrice)
</div>
<div class="display-label">Is Active</div>
<div class="display-field">
#Html.DisplayFor(m => m.IsActive)
</div>
#using (Html.BeginForm("Delete", "Service", null, FormMethod.Post, new { id = "deleteService" }))
{
<p>
<input type="submit" id="btnSubmit" value="Delete" />
</p>
}
<div>
#Html.ActionLink("Back", "Index", new { manage = "yes" })
</div>
<div id="dialog-confirm" title="Delete this service?" class="hidden">
<p>This service will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using YardLad.Models.Domain;
namespace YardLad.Models.View
{
public class ServiceViewModel
{
[Display(Name = "Service Id")]
public int ServiceId { get; set; }
[Required(ErrorMessage = "please enter a name")]
public string Name { get; set; }
[UIHint("multilinetext")]
public string Description { get; set; }
[Display(Name = "Base Price")]
public decimal BasePrice { get; set; }
[Display(Name = "Service Category")]
[Required(ErrorMessage = "please select a category")]
public int ServiceCategoryId { get; set; }
[Display(Name = "Is Active?")]
public bool IsActive { get; set; }
[Display(Name = "Service options")]
public List<ServiceOption> ServiceOptions { get; set; }
}
public class RequestServiceViewModel
{
[Required(ErrorMessage = "please select a state")]
public int StateId { get; set; }
[Required(ErrorMessage = "please select a service area")]
public int ServiceAreaId { get; set; }
[Required(ErrorMessage = "please select a service")]
public int ServiceId { get; set; }
[Required(ErrorMessage = "please indicate the items selected")]
public string[] SelectedServiceOptionItemIds { get; set; }
[Required(ErrorMessage = "please indicate the contractors available for the request")]
public string[] AvailableContractorIds { get; set; }
public State SelectedState { get; set; }
public ServiceArea SelectedServiceArea { get; set; }
public Service SelectedService { get; set; }
public List<ServiceOption> SelectedServiceOptions { get; set; }
public List<ServiceOptionItem> SelectedServiceOptionItems { get; set; }
public List<Contractor> AvailableContractors { get; set; }
public int SelectedContractorId { get; set; }
public Contractor SelectedContractor { get; set; }
public int SelectedContractorServiceId { get; set; }
public ContractorService SelectedContractorService { get; set; }
public decimal SubTotal { get; set; }
public decimal Tax { get; set; }
public decimal SelectedContractorTaxRate { get; set; }
public decimal Total { get; set; }
public bool UserIsLoggedIn { get; set; }
public int UserAddressId { get; set; }
public Address UserAddress { get; set; }
public bool CreateCustomAddress { get; set; }
public Address CustomAddress { get; set; }
}
public class SelectContractorViewModel
{
public int ServiceAreaId { get; set; }
public ServiceArea SelectedServiceArea { get; set; }
public int ServiceId { get; set; }
public Service SelectedService { get; set; }
public List<ServiceOption> ServiceOptions { get; set; }
public List<ServiceOptionItem> ServiceOptionItems { get; set; }
public List<Contractor> AvailableContractors { get; set; }
public Contractor SelectedContractor { get; set; }
public int ContractorTypeId { get; set; }
public int ContractorServiceId { get; set; }
public ContractorService SelectedContractorService { get; set; }
public List<ContractorServiceOption> ContractorServiceOptions { get; set; }
public List<ContractorServiceOptionItem> ContractorServiceOptionItems { get; set; }
public decimal SubTotal { get; set; }
public decimal Tax { get; set; }
public decimal SelectedContractorTaxRate { get; set; }
public decimal Total { get; set; }
}
}
Image of DB relations:
edmx
Thank You for Reading
Your Service is related to ContractorService as well and there must be some child records in there to cause the error you posted. You'll need to remove all of those children like you did the other tables, but you also need to set the child entity to Deleted:
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirm(int id)
{
var serviceToDelete = db.Services.Where(s => s.ServiceId == id).Single();
// remove the service option items
var serviceOptionItems = db.ServiceOptionItems.Where(soi => soi.ServiceOption.ServiceId == serviceToDelete.ServiceId);
foreach (var serviceOptionItem in serviceOptionItems)
{
db.ServiceOptionItems.Remove(serviceOptionItem);
db.Entry(serviceOptionItem).State = EntityState.Deleted;
}
// remove the service options
var serviceOptions = db.ServiceOptions.Where(so => so.ServiceId == serviceToDelete.ServiceId);
foreach (var serviceOption in serviceOptions)
{
db.ServiceOptions.Remove(serviceOption);
db.Entry(serviceOption).State = EntityState.Deleted;
}
// remove the contractor services
var contractorServices = db.ContractorServices.Where(so => so.ServiceId == serviceToDelete.ServiceId);
foreach (var contractorService in contractorServices)
{
db.ContractorServices.Remove(contractorService);
db.Entry(contractorService).State = EntityState.Deleted;
}
// remove the service
db.Services.Remove(serviceToDelete);
// save all changes
db.SaveChanges();
return RedirectToAction("Index", new { manage = "yes", mode = "all" });
}
You have a foreign key constraint on the tables Service, ServiceOptions and ServiceOptions. Thus you will have to delete all the ServiceOptionsItems and ServiceOptions of that service before you can delete the service.
But if you have such requirement, I suggest you use ON DELETE CASCADE while adding the constraint. So that it will allow you to directly delete the service and will delete all the child ServiceOptions and ServiceOptionsItems automatically.
More Info: http://www.mysqltutorial.org/mysql-on-delete-cascade/
From the error message, it looks like you have the association between Service and something called ContractorService. Delete the related ContactorService entities first or remove or change its ServiceId value.
Hi I have been looking for a solution to this problem but I had no luck. Using my viewmodel POST can not get the data, no matter how you do always the object is null. I'll put the code so you can see to which I refer.
This is my ViewModel
public class ProyectosCompletos
{
public IEnumerable<Proyecto> Proyectos { get; set; }
public IEnumerable<Informacion> Informaciones { get; set; }
public IEnumerable<Diseno> Disenos { get; set; }
public IEnumerable<Procedimiento> Procedimientos { get; set; }
public IEnumerable<Programacion> Programaciones { get; set; }
public IEnumerable<Instalacion> Instalaciones { get; set; }
}
This is the model project, it would be the "main" model
public class Proyecto
{
public int ProyectoID { get; set; }
public string Titulo { get; set; }
public virtual ICollection<Elaboracion> Elaboraciones { get; set; }
public virtual Procedimiento Procedimiento { get; set; }
public virtual Informacion Informacion { get; set; }
public virtual Instalacion Instalacion { get; set; }
public virtual Diseno Diseno { get; set; }
public virtual Programacion Programacion { get; set; }
}
This is for example the Instalacion model, and the others are similar
public class Instalacion
{
[Key]
[ForeignKey("Proyecto")]
public int ProyectoID { get; set; }
public double HardwareNota { get; set; }
public double SoftwareNota { get; set; }
public virtual Proyecto Proyecto { get; set; }
public virtual ICollection<InstalacionEntrada> Entradas { get; set; }
public virtual ICollection<InstalacionAnotacion> Anotaciones { get; set; }
}
This is the Controller
public ActionResult Docente(int? ListaProyectos)
{
//This code is not relevant to the problem
var viewModel = new ProyectosCompletos();
string usuarioActualId = User.Identity.GetUserId();
ApplicationUser usuarioActual = db.Users.FirstOrDefault(x => x.Id == usuarioActualId);
var pro = db.Elaboraciones
.Where(e => e.ApplicationUserID == usuarioActual.Id)
.Select(e => new { e.ProyectoID, e.Proyecto.Titulo});
ViewBag.ListaProyectos = new SelectList(pro, "ProyectoID", "Titulo");
//THIS IS WHAT MATTERS
if (ListaProyectos != null)
{
ViewBag.ProyectoID = ListaProyectos.Value;
viewModel.Proyectos = db.Proyectos.Where(p => p.Archivar == false && p.ProyectoID == ListaProyectos.Value);
viewModel.Informaciones = db.Informaciones.Where(i => i.ProyectoID == ListaProyectos.Value);
viewModel.Procedimientos = db.Procedimientos.Where(i => i.ProyectoID == ListaProyectos.Value);
viewModel.Disenos = db.Disenos.Where(i => i.ProyectoID == ListaProyectos.Value);
viewModel.Programaciones = db.Programaciones.Where(i => i.ProyectoID == ListaProyectos.Value);
viewModel.Instalaciones = db.Instalaciones.Where(i => i.ProyectoID == ListaProyectos.Value);
}
return View(viewModel);
}
For GET no problem to get the data. I get them properly and see the view
public ActionResult Docente(int ListaProyectos, ProyectosCompletos viewModel)
{
if (ModelState.IsValid)
{
db.Entry(viewModel.Informaciones).State = EntityState.Modified;
db.Entry(viewModel.Disenos).State = EntityState.Modified;
db.Entry(viewModel.Procedimientos).State = EntityState.Modified;
db.Entry(viewModel.Programaciones).State = EntityState.Modified;
db.Entry(viewModel.Instalaciones).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Docente");
}
}
But to return to the POST form the object is completely empty.
Finally I put the view, I will reduce it a bit because it is already long enough question
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
foreach (var item in Model.Proyectos)
{
<h3>#item.Titulo</h3>
#if (Model.Instalaciones != null)
{
foreach (var instalacion in Model.Instalaciones)
{
Nota: #Html.EditorFor(m => instalacion.HardwareNota, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => instalacion.HardwareNota, "", new { #class = "text-danger" })
Nota: #Html.EditorFor(m => instalacion.SoftwareNota, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => instalacion.SoftwareNota, "", new { #class = "text-danger" })
}
}
}
<input type="submit" value="Guardar Cambios" class="btn btn-success" />
}
I hope you can help me out, thanks !!
I am trying to pull a list from my ViewModel to populate a drop-down. I can get the objects from the Model and pass them to the View, but the view just shows the name of the ViewModel as the value in the dropdown. Not sure how to get the actual values to the Dropdown or if am going in the wrong direction. No intellesence past the definition of the object "model.InitialFeesChart". Thanks in advance for looking.
Controller: Objects contain needed data
public ActionResult CreateFranchise()
{
var model = new FranchiseVM();
model.FranStates = new List<string> { "AZ", "NV", "CA" };
//Grap the Package Identificaton to determine Package selected by Franshise
model.InitialFeesChart = (from f in _db.InitalFeesCharts
select new InitalFeesChartVM {IFCPackage = f.IFCPackage}).ToList();
return View(model);
}
ViewModel:
namespace Compass.Models
{
public class FranchiseVM
{
[Key]
public int FranchiseID { get; set; }
public string FranPID { get; set; }
public string FranBusinessName { get; set; }
public string FranAddress { get; set; }
public string FranCity { get; set; }
public string FranState { get; set; }
public string FranPostalCode { get; set; }
public string FranPhonePrimary { get; set; }
public string FranPhonePrimaryCell { get; set; }
public string FranFAX { get; set; }
public string FranOwnerFirstName { get; set; }
public string FranOwnerLastName { get; set; }
public string FranAlternateFirstName { get; set; }
public string FranAlternateLastName { get; set; }
public string FranAlternatePhone { get; set; }
public string FranNotes { get; set; }
public string IFCPackageCurrent { get; set; }
public IList<string> FranStates { get; set; }
//public IList<InitalFeesChartVM> InitialFeesChart { get; set; }
//Added
public string IFCPackage { get; set; }
private readonly List<InitialFeesChart> _InitialFeesChart;
public IEnumerable<SelectListItem> IFCItems
{
get { return new SelectList(_InitialFeesChart, "InitialFeesID", "IFCPackage"); }
}
}
}
View:
<div class="form-group">
#Html.LabelFor(model => model.IFCPackageCurrent, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.IFCPackageCurrent, Model.IFCItems))
</div>
</div>
Final working code:
ViewModel
public IList<InitalFeesChartVM> InitialFeesChart { get; set; }
[Display(Name = "Franchise Package")]
public string IFCPackageCurrent { get; set; }
View:
<div class="form-group">
#Html.LabelFor(model => model.IFCPackageCurrent, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.IFCPackageCurrent, new SelectList(Model.InitialFeesChart, "InitialFeesID", "IFCPackage"))
</div>
</div>
Controller:
public ActionResult CreateFranchise()
{
var model = new FranchiseVM();
model.FranStates = new List<string> { "AZ", "NV", "CA" };
model.InitialFeesChart = (from f in _db.InitalFeesCharts select new InitalFeesChartVM { IFCPackage = f.IFCPackage, InitialFeesID = f.InitialFeesID }).ToList();
return View(model);
You need to specify what properties to use in the Select List. Specify the value field and the text field like this: SelectList(Items, "Id", "Title")
I've created a fiddle that uses your classes. You will have to change the string values in the part when the select list is created so that they match the properties you want to use from your InitalFeesChartVM http://dotnetfiddle.net/9052ZH