Dynamically binding Drop Down List in MVC 4 - asp.net-mvc-4

I trying to create a drop down list and bind it to the values fetched from database.
How can I do this. I have done following till now. I want the value of the items of the dropdown ie c.ID in following code to be bind with the Currency_ID of the CountryVM.
public CountryVM()
{
[DisplayName("Country ID")]
[Required]
public string ID { get; set; }
[Required]
[DisplayName("Description")]
public string Description { get; set; }
[DisplayName("Currency Id")]
public Nullable<int> Currency_ID { get; set; }
}
//Controller
DAL library = new DAL();
var items = library.GetAllCurrency(Library.Filter.CURRENCY_SYMBOL);
IEnumerable<SelectListItem> list = items.Select(c => new SelectListItem { Text = c.CURRENCY_SYMBOL, Value = c.ID.ToString() });
ViewBag.curr_symbol = list;
return View();
//In View I am trying to access my DropDown as follows :
#Html.DropDownListFor(model => model.Currency_ID,"curr_symbol" )// how to write this.

Do like this in view:
#
{
SelectList CurrencyList = (SelectList)ViewBag.curr_symbol;
}
#Html.DropDownListFor(model => model.Currency_ID,CurrencyList)
and in action:
IEnumerable<SelectListItem> list = items.Select(c => new SelectListItem { Text = c.CURRENCY_SYMBOL, Value = c.ID.ToString() }).ToList();
or:
var list = (from c in items
select new SelectListItem {Text = c.CURRENCY_SYMBOL,
Value = c.ID.ToString() }).ToList();
Update:
As you told in discussion that it is throwing exception on form post so what you need is to fill the List again and put it in ViewBag in post action as from ViewBag it is removed.

Related

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>

ASP.NET MVC cannot get dropdownlist to set selected value

In my ASP.NET MVC application, I have a drop-down list in a form on a page, where the dropdown list item that should be selected when the page loads don't get selected.
The ViewModel for the page has a property for the list of SelectListItems that should be used to populate the drop-down list:
See below for the View model and illustration of the "Index" class, which has HeaderItemID as one of it's properties:
public class IndexItemResult
{
public Index FocalIndex { get; set; }
public string FocalIndexHeaderItemText { get; set; }
public List<Item> IndexItems { get; set; }
public List<SelectListItem> ItemSelectList { get; set; }
public List<Item> ItemList { get; set; }
public IndexItemResult() { }
}
public class Index
{
public int IndexID { get; set; }
public string IndexName { get; set; }
public int IndexHeaderItemID { get; set; }
}
I set the "text", "value", and "selected" properties of items in the SelectListItems from a database LINQ query in my controller. This method also sets the "FocalIndex" property of the ViewModel. As HeaderItemID is a property of FocalIndex, I therefore assumed that "HeaderItemID" is available as a field that can be bound to.
"HeaderItemID" is the item that should be selected. When I look at the list of SelectListItems that gets generated, everything looks ok - the "text" and "value" properties are all fine, and the correct item is specified as "selected".
private IndexItemResult GetIndexItemResult(int? indexID)
{
IndexItemResult indexItemResult = new IndexItemResult();
Index focalIndex = db.Indexes.Find(indexID);
indexItemResult.FocalIndex = focalIndex;
int HeaderItemID = focalIndex.IndexHeaderItemID;
indexItemResult.ItemSelectList = db.ItemTexts.
Where(it => it.LanguageID == 1).
Select(iText =>
new SelectListItem
{
Selected =
(
iText.ItemID == HeaderItemID ? true : false
),
Value = iText.ItemID.ToString(),
Text = String.Concat(iText.ID.ToString(), " ", iText.Text)
}).ToList();
return indexItemResult;
}
I then have a form on the page, where I specify the dropdown list with the #Html.DropDownList helper. I pass the list of SelectListItems from the ViewModel in the second parameter.
#Html.DropDownList("IndexHeaderItemID", Model.ItemSelectList,
htmlAttributes: new { #class = "form-control", #id = "HeaderItemDDL" })
The drop-down list renders with all the items as expected, but the item that should be set at "selected" is not selected. Instead, the first item is selected. Any suggestions for what I'm missing here?
I see no place where you're actually setting anything in ModelState named IndexHeaderItemID. Since that is the name you're binding to, then one of Request["IndexHeaderItemID"], ViewData["IndexHeaderItemID"], ViewBag.IndexHeaderItemID or Model.IndexHeaderItemID must be set to the value you expect to be selected.

How to bind hard coded dropdownlist value into database using MVC4?

I have created dropdownlist which populates countries name and value of country name is hardcoded. Now i want selected country name has to be stored in database. Can anyone help me please? I tried below code in Get method,
SelectListItem item;
List<SelectListItem> CountryList = new List<SelectListItem>();
item = new SelectListItem();
item.Text = "India";
item.Value = "1";
myList.Add(item);
item = new SelectListItem();
item.Text = "Italy";
item.Value = "0";
CountryList.Add(item);
ViewBag.country = CountryList;
return View();
Model :
public class Createcountry
{
[Table("mytable", Schema = "public")]
public class Create
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int regionid { get; set; }
public string countryname { get; set; }
}
}
View:
#Html.DropDownListFor(m => m.countryname, (IEnumerable<SelectListItem>)ViewBag.country, "select country");

MVC Filter Drop Down List Based on user response

I'm brand new to MVC and i'm trying get my dropdown list to dynamically change based on the value a user selects from a list before. The change is just a filter of the list based on the value chosen. I feel like there should be a way to filter my list based on the drop down picked i just am not sure how to do that. It seems like I should be able to write a js function on the view that does something like this:
function
{
selectedItem()
if x == "ListItemValue"
var CatListItems = new List<SelectListItem>();
CatListItems.Add(new SelectListItem { Text = String.Empty, Value = String.Empty });
foreach (var ZCategory in ViewBag.ZCategory)
if CaTlistItems.CategoryForeignKeyID = 3
{
CatListItems.Add(new SelectListItem { Text = ZCategory, Value = ZCategory });
}
}
Here is my code so far:
Model
public class ArmyRace
{
[Key]
public int RaceID { get; set; }
public string Race { get; set; }
public virtual ItemCategory ItemCategory { get; set; }
}
public class ItemCategory
{
[Key]
public int CategoryID { get; set; }
public string ArmyCategory { get; set; }
}
Controller:
List<string> Category = new List<string>(2);
var ICategory = from i in db.ItemCategory
select i;
foreach (var x in ICategory)
{
Category.Add(x.ArmyCategory);
}
ViewBag.ZCategory = Category;
View
var CatListItems = new List<SelectListItem>();
CatListItems.Add(new SelectListItem { Text = String.Empty, Value = String.Empty });
foreach (var ZCategory in ViewBag.ZCategory)
{
CatListItems.Add(new SelectListItem { Text = ZCategory, Value = ZCategory });
}
What I ended up doing for this one is creating 4 seperate lists. One with everything in the dropdown and 3 with the filters i wanted. I then used the simple $jquery.hide() and show functions to show or hide the ones I wanted. Finally i had to change the ID using the $jquery.attr() function for the list that is not active so the POST method would add the correct item to the database.
I believe this is not the ideal way, if I could have somehow brought my lists over with some type of identifier so i could parse through them on the view that would have been ideal but i didn't see a way of doing this.

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