I am new to mvc4 and trying to generate dropdownlist dynamically. I want to create a list for next 10 years. Where my understanding gone wrong?
Model
using System.Web.Mvc;
using DropDownList.Models;
namespace DropDownList.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ddlist DropList = new ddlist();
var years = Enumerable.Range(DateTime.Now.Year, 10);
var select = new SelectList(years.Select(y => new SelectListItem()
{
Text = y.ToString(),
Value = y.ToString()
}));
DropList.CountryList = select.ToList();
return View(DropList);
}
}
}
----------Controller-----
using System.Text;
using System.Web.Mvc;
namespace DropDownList.Models
{
public class ddlist
{
[Required(ErrorMessage = "Please select a Country")]
public string CountryCode { get; set; }
public IEnumerable<SelectListItem> CountryList
{
get;
set;
}
}
}
-------------View-----------------
#model DropDownList.Models.ddlist
#{
Layout = null;
}
#Html.DropDownListFor(
model => model.CountryCode,
Model.CountryList, "select"
)
#Html.ValidationMessageFor(model => model.CountryCode
Following are the output. what i am expecting to see years like 2014, 2015..
select
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
System.Web.Mvc.SelectListItem
It's more likely to return a SelectList
1) Change the model to:
public class ddlist
{
[Required(ErrorMessage = "Please select a Country")]
public string CountryCode { get; set; }
public SelectList CountryList
{
get;
set;
}
}
2) And then return the list as SelectList to the model:
public ActionResult Index()
{
DropList ddlist = new ddlist();
var years = Enumerable.Range(DateTime.Now.Year, 10);
var select = new SelectList(years.Select(y => new SelectListItem()
{
Text = y.ToString(),
Value = y.ToString()
}));
DropList.CountryList = select; //Removing the ToList and Using the SelectList
return View(DropList);
}
Related
i am trying to filter my view for a couple of hours by now. This is what i have:
My View:
#using (Html.BeginForm("Index", "RH_CentroCusto", FormMethod.Get))
{
#Html.DropDownListFor(f => f.DepartmentoSelecionado , Model.Departamentos, "Select")
}
in my Model Class :
public IEnumerable<SelectListItem> Departamentos { get; set; }
public string DepartmentoSelecionado { get; set; }
My controller:
//i want to receive the value in departamentoSelecionado !!
public IActionResult Index( string searchString, string departamentoSelecionado = "", int page = 1)
List<SelectListItem> selectList = new List<SelectListItem>();
foreach (var x in _context.RH_Departamento.ToList())
{
selectList.Add(new SelectListItem() { Text = x.Departamento , Value = x.Departamento });
}
//and then i add to the viewModel that i create the list
ViewModelCentroCusto vmcc = new ViewModelCentroCusto()
{
Departamentos = selectList
}
When i try to select one and click enter, it is suposed to be passing because in my browser i inspected and it was passing query parameters:
But in my controller my departamentoSelecionado is null, also the dropdown list gets the "select" again instead of keeping what i choose before! Any help is appreciated!
Change departamentoSelecionado to departmentoSelecionado . You spelt an extra letter a in departmentoSelecionado .
//public IActionResult Index( string searchString, string departamentoSelecionado = "", int page = 1)
public IActionResult Index( string searchString, string departmentoSelecionado = "", int page = 1)
The parameter in action method should be same as f => f.DepartmentoSelecionado.
Update 16/09/2020
Codes of controller
public class RH_CentroCustoController : Controller
{
//i want to receive the value in departamentoSelecionado !!
public IActionResult Index(string searchString, string departmentoSelecionado ="", int page = 1)
{
List<SelectListItem> selectList = new List<SelectListItem>();
IList<RH_Departamento> RH_Departamento = new List<RH_Departamento>(){
new RH_Departamento(){ Departamento="dep1" },
new RH_Departamento(){ Departamento="dep2" },
new RH_Departamento(){ Departamento="dep3" },
};//just for test
//foreach (var x in _context.RH_Departamento.ToList())
foreach (var x in RH_Departamento.ToList())
{
selectList.Add(new SelectListItem() { Text = x.Departamento, Value = x.Departamento });
}
//and then i add to the viewModel that i create the list
ViewModelCentroCusto vmcc = new ViewModelCentroCusto()
{
Departamentos = selectList
};
return View(vmcc);
}
}
Codes of View
#model xxx.Models.ViewModelCentroCusto
#{
Layout = null;
}
#using (Html.BeginForm("Index", "RH_CentroCusto", FormMethod.Get))
{
#Html.DropDownListFor(f => f.DepartmentoSelecionado, new SelectList(Model.Departamentos, "Value", "Text"), "Select");
<input type="submit" value="Save" />
}
Codes of Model
public class ViewModelCentroCusto
{
public IEnumerable<SelectListItem> Departamentos { get; set; }
public string DepartmentoSelecionado { get; set; }
}
public class RH_Departamento
{
public string Departamento { get; set; }
}
Test
when click edit link in index page
it give me error
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.Employee_2EF71CC17A29BA91B02BC5CDB0EE5AF82D363EEF7E174A21C9546772913AA929', but this dictionary requires a model item of type 'WebCourse.Models.Customemployee'.
I have custom model Customemployee
namespace WebCourse.Models Customemployee
{
public class Customemployee
{
//represent employee table in database
public string Name { get; set; }
public int Salary { get; set; }
public string Email { get; set; }
public int DistrictId { get; set; }
//represent employee course table in database
public List<EmployeeCourse> Courses { get; set; }
//represent employee language table in database
public List<EmployeeLangage> Langs { get; set; }
}
}
and my controller empcourse
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebCourse.Models;
using System.Data.Entity;
namespace WebCourse.Controllers
{
public class empcourseController : Controller
{
mycourseEntities db = new mycourseEntities();
// GET: empcourse
public ActionResult Index()
{
var query = db.Employees.ToList().Select(p => new EmpInfo
{
Id = p.Id,
Name = p.Name,
Salary = Convert.ToInt32( p.Salary),
Email = p.Email,
DistrictName = p.Destrict.DistrictName,
CityName = p.Destrict.City.CityName,
CountryName = p.Destrict.City.Country.CountryName,
CourseNames = p.EmployeeCourses.Select(t => t.Course.CourseName).ToList(),
LanguageName = p.EmployeeLangages.Select(t => t.Language.LnaguageName).ToList(),
levelName = p.EmployeeLangages.Select(t => t.Level.LevelName).ToList(),
CourseName = string.Join(",", p.EmployeeCourses.Select(t => t.Course.CourseName).ToList())
});
return View(query);
}
public ActionResult Create()
{
ViewBag.CountryId = new SelectList(db.Countries, "Id", "CountryName");
ViewBag.LanaguageId = new SelectList(db.Languages.ToList(), "Id", "LnaguageName");
ViewBag.LevelId = new SelectList(db.Levels.ToList(), "Id", "LevelName");
ViewBag.CourseId = new SelectList(db.Courses.ToList(), "Id", "CourseName");
return View();
}
public ActionResult Edit(int id)
{
//how to pass data from index view to edit view
Employee old = db.Employees.Find(id);
return View(old);
}
[HttpPost]
public ActionResult Create(Customemployee cemp)
{
using (mycourseEntities db = new mycourseEntities())
{
Employee E = new Employee { Name = cemp.Name, Salary = cemp.Salary, Email = cemp.Email, DistrictId = cemp.DistrictId };
foreach (var i in cemp.Courses)
{
E.EmployeeCourses.Add(i);
db.SaveChanges();
}
foreach (var i in cemp.Langs)
{
E.EmployeeLangages.Add(i);
db.SaveChanges();
}
db.Employees.Add(E);
db.SaveChanges();
}
return View();
}
public JsonResult getcitybyid(int id)
{
db.Configuration.ProxyCreationEnabled = false;
return Json(db.Cities.Where(a => a.CountryId == id), JsonRequestBehavior.AllowGet);
}
public JsonResult getdistrictbyid(int id)
{
db.Configuration.ProxyCreationEnabled = false;
return Json(db.Destricts.Where(a => a.CityId == id), JsonRequestBehavior.AllowGet);
}
}
}
the error show here in code
public ActionResult Edit(int id)
{
//how to pass data from index view to edit view
Employee old = db.Employees.Find(id);
return View(old);
}
How to pass data from index view that show data to edit view
From the error message, it looks like your Edit view is strontly typed to Customemployee type. That means you should be passing an object of Customemployee class from your Edit action method to this view. But your current code is sending an object of Employee type.
So update your Edit action method to send the correct object to the view.
public ActionResult Edit(int id)
{
Employee old = db.Employees.Find(id);
if(old!=null)
{
var vm = new CustomEmployee();
vm.Name = old.Name;
vm.Email = old.Email;
// Assign other property values as needed.
return View(vm);
}
return Content("No employees found for the Id passed");
// to do : Ideally return a "NotFound" view
}
I am getting dynamic values in dropdownlist through viewbag,dropdownlist values is displaying properly but my problem is posting,I am getting problem to insert dropdownlist values in sql server,please help me to solve this problem.
This is my model page,
public class RegisterModel
{
public Prefix Prefix { get; set; }
}
public class Prefix
{
public int? ID { get; set; }
public string Name { get; set; }
}
This is my controller page,
void BindPrefix()
{
List<Prefix> lstPrefix = new List<Prefix>()
{
new Prefix { ID = null, Name = "Select" },
new Prefix { ID = 1, Name = "Mr" },
new Prefix { ID = 2, Name = "Ms" },
new Prefix { ID = 1, Name = "Mrs" },
new Prefix { ID = 2, Name = "Dr" }
};
ViewBag.Prefix = lstPrefix;
}
public ActionResult Register()
{
BindPrefix();
return View();
}
[HttpPost]
public ActionResult Register(FormCollection FC)
{
string Prefix =FC[ViewBag.Prefix]; // here prefix get null value.
return view();
}
This is my view page,
#Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef))
If you are trying to get Selected Value,You have to get from the Drop down name which generate:
string Prefix =FC["Prefix"];
Currently this :
#Html.DropDownListFor(m => m.Prefix.ID, new SelectList(ViewBag.Prefix, "ID", "Name", ViewBag.pef))
will generate this html:
<select id="Prefix_ID" name="Prefix.ID">
.........
.........
</select>
and using Element name in form Collection will give you the value.
string Prefix =FC["Prefix.ID"].ToString();
Based on the comments that you only want to display and post back a 'title', the use of class Prefix seems unnecessary
View model
public class RegisterViewModel
{
[Required(ErrorMessage = "Please select a title")]
public string Title { get; set }
// other properties
public SelectList TitleList { get; set; }
}
Controller
public ActionResult Register()
{
RegisterViewModel model = new RegisterViewModel();
ConfigureViewModel(model);
return View(model);
}
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if(!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
// save and redirect
}
private void ConfigureViewModel(RegisterViewModel model)
{
List<string> titles = new List<string>) { "Mr.", "Ms", "Mrs", "Dr." };
model.TitleList = new SelectList(titles);
}
View
#model RegisterViewModel
...
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Title)
#Html.DropDownListFor(m => m.Title, Model.TitleList, "-Please select-")
#Html.ValidationMessageFor(m => m.Title)
....
}
I've been trying to populate a dropdownlist for a while now and would appreciate some help. I have my model and viewmodel and my trying to populate the Dropdownlist and send it to the view so a user can choose a cartype and click submit.
public class Cars
{
public int CarId { get; set; }
public string Name { get; set; }
}
public class CarViewModel
{
public int SelectedCarId { get; set; }
public IEnumerable<SelectListItem> CarTypes;
}
public ActionResult FillDropDown()
{
var model = new ViewModel();
model.CarTypes = (from s in context.CarTypes
select new SelectListItem()
{
Text = s.Name,
Value = SqlFunctions.StringConvert((double)s.Id).Trim(),
}).ToList<SelectListItem>();
return View(model);
}
So I would like some help how to render this in the view. I tried the following but I get a nullreference exception.
#Html.BeginForm("FillDropDownList","Home", FormMethod.Post,null)
{
#Html.DropDownListFor(x => x.SelectedCarId, Model.CarTypes);
<input type="submit" value="submit" />
}
Try to use CarViewModel instead of ViewModel.
public ActionResult FillDropDown()
{
var model = new CarViewModel(); //CarViewModel instead of ViewModel
model.CarTypes = (from s in context.CarTypes
select new SelectListItem()
{
Text = s.Name,
Value = SqlFunctions.StringConvert((double)s.Id).Trim(),
}).ToList<SelectListItem>();
return View(model);
}
EDIT:
Change your IEnumerable property in CarViewModel into SelectList
public class CarViewModel
{
public int SelectedCarId { get; set; }
public SelectList CarTypes;
}
Make sure the SelectListItem is not null, in the FillDropDown() method.
I have a custom model (let's say CustomModel) for populating my razor DropDownList in the view:
namespace MyNamespace.Models
{
public class SelectListItem
{
public string Value { get; set; }
public string Text { get; set; }
}
public class ComponentTypeModel
{
private readonly List<ComponentType> componentTypes;
[Display(Name = "Component Type")]
public int SelectedCompTypeId { get; set; }
public IEnumerable<SelectListItem> CompTypeItems
{
get
{
var allCompTypes = componentTypes.Select(f => new SelectListItem
{
Value = f.Id.ToString(),
Text = f.Name
});
return allCompTypes;
}
}
public IEnumerable<SelectListItem> DefaultCompTypeItem
{
get
{
return Enumerable.Repeat(new SelectListItem
{
Value = "-1",
Text = "Select a component type"
},
count: 1);
}
}
}
}
Then in my view I do the following using razor:
#model MyNamespace.Models.CustomModel
#Html.LabelFor(m => m.SelectedCompTypeId);
#Html.DropDownListFor(m => m.SelectedCompTypeId, Model.CompTypeItems);
but the second argument Model.CompTypeItems in line:
#Html.DropDownListFor(m => m.SelectedCompTypeId, Model.CompTypeItems);
is generating a compilation error saying that it is not valid. Any ideas?
I think you are complicating yourself.
Just use this model:
public class ComponentTypeModel
{
public int? SelectedComp {get; set;}
public SelectList DDLCompTypes {get; set;}
}
Then in your controller:
var model = new ComponentTypeModel();
model.DDLCompTypes = new SelectList(theComponentTypes, "Id","Name");
//If you need to set some value in the DropDownValue (for instance in the Edit view) you do:
model.DDLCompTypes = new SelectList(theComponentTypes, "Id","Name", model.SelectedComp);
Then in your View:
#Html.DropDownFor(x => x.SelectedComp, Model.DDLCompTypes, "Select a component type" )