Populating razor DropDownList from view model - asp.net-mvc-4

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" )

Related

HTML.DropDownListFor not passing parameter to controller?

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

How do i load data to a drop down on view that already bound with a collection?

i have a view that is bound with the IEnumerable<ProductCategoryViewModel>
in this view there is a drop down box with the values search type values so i can search a product category by either code or name.
here is the controller:
public ActionResult Index()
{
List<SelectListItem> list = new List<SelectListItem> {
new SelectListItem {Text="By Code", Value="1", Selected=true},
new SelectListItem {Text="By Name", Value="2"}
};
var categories = _db.mt_ProductCategories
.Select(
p => new ProductCategoriesViewModel
{
Id = p.Id,
Name = p.CatName,
CatCode = p.CatCode, SearchTypes=list
});
if (Request.IsAjaxRequest())
{
return PartialView("_ProductCategoryList", categories);
}
return View(categories);
}
here is the ViewModel
public class ProductCategoriesViewModel
{
public int Id { get; set; }
public string CatCode { get; set; }
public string Name { get; set; }
public IEnumerable<SelectListItem> SearchTypes { get; set; }
public string SearchType { get; set; }
}
here is view
#model IEnumerable<eComm1.Models.ProductCategoriesViewModel>
#using (Ajax.BeginForm("Search", "ProductCategory",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "prod-grid",
InsertionMode = InsertionMode.Replace,
OnSuccess = "loaddivdata"
}))
{
//i need to put the drop down here but since i passed a collection it does not show the property "SearchType". the code should be like below but errors
#Html.DropDownListFor(m=>m.SearchType, Model.SearchTypes)
}
How do i access the property SearchType in my current view?
You need a view model that has properties for SearchType and SearchType and in the view use a single instance of that view model (and initially generate the list of ProductCategories by calling #Html.Action()).
public class ProductSearchVM
{
public string searchText { get; set; }
public string SearchType { get; set; }
public IEnumerable<SelectListItem> SearchTypes { get; set; }
}
and in the controller
public ActionResult Index()
{
ProductSearchVM model = new ProductSearchVM
{
SearchType = "1", // this is how you set the selected value
SearchTypes = new List<SelectListItem>
{
new SelectListItem { Text = "By Code", Value = "1" }, // no point adding Selected = true; - its ignored by the HtmlHelper
new SelectListItem { Text = "By Name", Value = "2" }
}
};
return View(model)
}
and in the view
#model ProductSearchVM
#using (Ajax.BeginForm("Search", "ProductCategory", new AjaxOptions { ... }))
{
#Html.DropDownListFor(m => m.SearchType, Model.SearchTypes)
#Html.TextBoxFor(m => m.searchText)
}
<div id="prod-grid">
#Html.Action("Search", "ProductCategory") // optionally add new { searchType = "1" }?
</div>

How to post dropdownlist viewbag values to sql server using mvc 4?

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)
....
}

ASP.NET MVC Populating dropdownlist

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.

Filling dropdownlist from DB

I'm trying to move over to MVC from webforms, and to be honest, it's not going very well.
I need a DropDownList populated with values from my database, and I'm having a hard time understanding how to do this.
I'm thinking, that I need to create a model,using entity framework, and refer my DropDownList to that? But how do I point it to that model?
Also, if I make a model, from a database table, how do I adjust the select command, so I only get certain values, and not the entire table?
I know this is kind of a broad question, and I have no examples listed, but I've had a really hard time, finding information I could understand, with regards to my issue.
I would start from this this should get you the project created if you have not done so so you can have the model ready
http://msdn.microsoft.com/en-us/data/gg685489
in order to create a dropdownlist here is an example
ViewBag.dropdownlist = new SelectList(db.tablename, "Valuefiled", "NameGField");
where Valuefiled=name of a column in your database that you want to use for values
"NameGField"=name of a column in your database that you want to use for names
getting drop down list to view
#Html.DropDownList("dropdownlist")
How About this
Your ViewModel
public class CategoryViewModel
{
public Category Category { get; set; }
public IEnumerable<SelectListItem> CategoryTitles { get; set; }
}
Your Controller
public ActionResult Create()
{
var categoryviewmodel = new CategoryViewModel();
categoryviewmodel.Category = new Category();
var list = categoryRepository.AllCategoryTitles().ToList().Select(t => new SelectListItem
{
Text = t.CategoryName,
Value = t.CategoryID.ToString()
})
.ToList();
list.Insert(0, new SelectListItem { Value = "0", Text = "Please Selext" });
categoryviewmodel.CategoryTitles = list;
return View(categoryviewmodel);
}
Your Repository
public IQueryable<Category> AllCategoryTitles()
{
var query = context.Categories.Where(m => m.ParentCategoryID == null && m.IsActive==true);
return query;
}
Your View
#Html.DropDownListFor(model => model.CategoryParentID, Model.CategoryTitles)
You can use a viewModel. Here is an example solution with some assumptions. Refer to the dropdownlist (here in the dropdown I am listing departments of type "InBound"
Employee Model
public class EmployeeModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int DeptId { get; set; }
}
Department Model
public class DepartmentModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
ViewModel (to be passed into the view)
public class EmployeeViewModel
{
public EmployeeModel Employee { get; set; }
public IEnumerable<DepartmentModel> Departments { get; set; }
}
Controller
public ActionResult Index()
{
EmployeeViewModel vm = new EmployeeViewModel();
//This is hardcoded. However you will write your own method to pull the department details with filtering
List<DepartmentModel> departments = new List<DepartmentModel>() { new DepartmentModel { Id = 1, Name = "Accounts", Type = "InBound" }, new DepartmentModel { Id = 2, Name = "Finance", Type = "OutBound" }, new DepartmentModel { Id = 3, Name = "HR", Type = "InBound" } };
vm.Departments = departments.Where(d => d.Type == "InBound");
return View(vm);
}
View
#model Test1.ViewModels.EmployeeViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.HiddenFor(model => model.Employee.Id);
<table>
<tr>
<td>#Html.LabelFor(model => model.Employee.FirstName)</td>
<td>#Html.EditorFor(model => model.Employee.FirstName)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Employee.LastName)</td>
<td>#Html.EditorFor(model => model.Employee.LastName)</td>
</tr>
<tr>
<td>#Html.Label("Department")</td>
<td>#Html.DropDownListFor(model => model.Employee.DeptId, new SelectList(Model.Departments, "Id", "Name"))</td>
</tr>
</table>
}