Drop down mvc3..wont populate the fields - c#

I have got this controller:
public class NewPostController : Controller
{
List<SelectListItem> languages= new List<SelectListItem>();
public ActionResult Index()
{
ViewData["languages"] = new SelectList(languages, "Text", "Value", 1);
return View();
}
private void GetCountryList()
{
CultureInfo[] cultureList = CultureInfo.GetCultures(CultureTypes.AllCultures);
foreach (CultureInfo culture in cultureList)
{
languages.Add(new SelectListItem
{
Text = culture.DisplayName,
Value = culture.DisplayName,
});
}
}
}
The list of items should be established by their languages and be passed to the view.
#Html.DropDownList("languages",null,
"** Please Select **",
new { #class = "my-select-css-class" })
Nothing gets populated..Why?

GetCountryList()
You never call it.

Related

MVC dynamic dropdown list not working,getting error "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'LocID'.'"

I'm trying to bind the dropownlist values from a database by using the below code, but it throwing error in view. I did the multiple exercises but couldn't reach the output. Can someone please help me with this?
Error:
There is no ViewData item of type 'IEnumerable' that has the key 'LocID'.'
Action Code:
public ActionResult Add()
{
List<Location> listObj = new List<Location>();
{
listObj = LocDrpDwnList();
};
List<SelectListItem> LocList = new List<SelectListItem>();
foreach(var item in listObj)
{
LocList.Add(new SelectListItem
{
Text = item.LocationName.ToString(),
Value = Convert.ToInt32(item.LocID).ToString()
}) ;
}
ViewBag.LocID = LocList;
return View();
}
Method to get the List Values from Database:
public List<Location> LocDrpDwnList()
{
SqlConnection db = new SqlConnection(conn);
string query = "SELECT * FROM Location";
SqlCommand cmd = new SqlCommand(query, db);
db.Open();
List<Location> loclist = new List<Location>();
using (IDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
Location obj = new Location();
if (dataReader["LocID"] != DBNull.Value)
{
if (dataReader["LocID"] != DBNull.Value) { obj.LocID = Convert.ToInt32(dataReader["LocID"]); }
if (dataReader["LocationName"] != DBNull.Value) { obj.LocationName = (string)dataReader["LocationName"]; }
loclist.Add(obj);
}
}
return loclist;
}
}
View for the Dropdown Control:
#Html.DropDownListFor(model => model.LocID, (IEnumerable<SelectListItem>)ViewBag.LocID , "Select Location", new { htmlAttributes = new { #class = "form-control" } })
Please modify your controller action as:
public ActionResult Add()
{
List<Location> listObj = LocDrpDwnList();
/*
// Doesn't hurt populating SelectListItem this way. But you don't need to do this here.
List<SelectListItem> LocList = new List<SelectListItem>();
foreach (var item in listObj)
{
LocList.Add(new SelectListItem
{
Text = item.LocationName.ToString(),
Value = Convert.ToInt32(item.LocID).ToString()
});
}
*/
ViewBag.LocID = (string?)null; //Set to some predefined locId selection, so when page is loaded, dropdown will be defaulted to this value.
ViewBag.LocList = LocList;
return View();
}
and then update your view as:
#{
var LocList = new SelectList(ViewBag.LocList, "Id", "Text");
string LocId = ViewBag.LocId ?? (string)null;
}
#Html.DropDownList(#LocId, #LocList , "Select Location", new { htmlAttributes = new { #class = "form-control" } })
Instead of using ViewBags, its good practice to use ViewModels like something below:
public class AddViewModel
{
public AddViewModel()
{
this.LocList = new List<LocationViewModel>();
}
public int? LocId { get; set; }
// Instead of LocationViewModel, you can go with your idea List<SelectListItem> and change controller action and view accordingly.
public List<LocationViewModel> LocList { get; set; }
}
public class LocationViewModel
{
public int LocId { get; set; }
public string LocationName { get; set; }
}
and your controller action will be:
public ActionResult Add()
{
List<Location> listObj = LocDrpDwnList();
List<LocationViewModel> LocList = new List<LocationViewModel>();
foreach (var item in listObj)
{
LocList.Add(new LocationViewModel
{
LocationName = item.LocationName.ToString(),
LocId = Convert.ToInt32(item.LocID).ToString()
});
}
/*
ViewBag.LocID = (string?)null; //Set to some predefined locId selection, so when page is loaded, dropdown will be defaulted to this value.
ViewBag.LocList = LocList;*/
return View(new AddViewModel{LocList = LocList});
}
and your view will be;
#using AddViewModel
#Html.DropDownList(m => m.LocId, new SelectList(Model.#LocList, "Id", "Text") , "Select Location", new { htmlAttributes = new { #class = "form-control" } })
I believe you are trying to create a entry in a Database after selecting a Value from a DROP DOWN LIST, If i'm not wrong your mentioned code of a Controller is not having the POST header, you have to create another Controller with the same name with {HttpPost} hearder.
Kindly find the below link for your reference, may be you will find any sort of help.
https://stackoverflow.com/questions/51551547/asp-mvc-model-entity-validation-does-not-displaying-required-error

There is no ViewData element of type « IEnumerable<SelectListItem>

I'm trying to create new product but is give me an error on
dropdown is not type of IEnumerable
I make some test
- change method Post to Get for see if data cross url or not and is get data fine
This is controller :
public ActionResult Ajouter()
{
db = new IdentityDBEntities2();
ViewBag.categ = new SelectList(db.Categories, "Id", "libelle");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Create")]
public ActionResult Ajouter([Bind(Include = "Ida,description,image,Userid,Idc,titre")] Article article, HttpPostedFileBase postedFile)
{
try
{
if (ModelState.IsValid)
{
if (postedFile != null)
{
db = new IdentityDBEntities2();
article.image = Convert.ToString(postedFile.ContentLength);
postedFile.InputStream.Read(System.Text.Encoding.Unicode.GetBytes(article.image), 0, postedFile.ContentLength);
string fileName = System.IO.Path.GetFileName(postedFile.FileName);
string FilePath = "~/Content/img/" + fileName;
postedFile.SaveAs(Server.MapPath(FilePath));
article.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
article.Idc = Convert.ToInt32(Request["Cab"]);
article.image = fileName;
db.Articles.Add(article);
ViewBag.categ = new SelectList(db.Categories, "Id", "libelle");
db.SaveChanges();
return RedirectToAction("Index");
}
}
else return View(article);
}
catch
{
return View();
}
return View();
}
- And this is Dropdown in view :
#Html.DropDownList("categ", null, "-- Select Category -- ", new { id = "subCategory" })
I'm already change dropdown content to
#Html.DropDownList("categ",(IEnumerable<SelectListItem>)ViewBag.Cab, "-- Select Category -- ", new { id = "subCategory" })
But Doesn't work . thanks
You assign to ViewBag.categ type of List<Selectlistitem>, you have to cast Viewbag this type.
//first create List<selectlistitem>
List<SelectListItem> selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem() { Value = "", Text = "Select" });
foreach (var item in db.Categories.ToList())
{
selectListItems.Add(new SelectListItem() { Value = item.Id.ToString(), Text = item.Name });
}
ViewBag.categ=selectListItems;
//use it in view
#Html.DropDownList("categ",(List<SelectListItem>)ViewBag.categ, "-- Select Category -- ", new { id = "subCategory" })
//with your code
public ActionResult Ajouter()
{
db = new IdentityDBEntities2();
List<SelectListItem> selectListItems = new List<SelectListItem>();
foreach (var item in db.Categories.ToList())
{
selectListItems.Add(new SelectListItem() { Value = item.Id, Text = item.libelle });
}
ViewBag.categ = selectListItems;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("Create")]
public ActionResult Ajouter([Bind(Include = "Ida,description,image,Userid,Idc,titre")] Article article, HttpPostedFileBase postedFile)
{
try
{
if (ModelState.IsValid)
{
if (postedFile != null)
{
db = new IdentityDBEntities2();
article.image = Convert.ToString(postedFile.ContentLength);
postedFile.InputStream.Read(System.Text.Encoding.Unicode.GetBytes(article.image), 0, postedFile.ContentLength);
string fileName = System.IO.Path.GetFileName(postedFile.FileName);
string FilePath = "~/Content/img/" + fileName;
postedFile.SaveAs(Server.MapPath(FilePath));
article.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
article.Idc = Convert.ToInt32(Request["Cab"]);
article.image = fileName;
db.Articles.Add(article);
List<SelectListItem> selectListItems = new List<SelectListItem>();
foreach (var item in db.Categories.ToList())
{
selectListItems.Add(new SelectListItem() { Value = item.Id, Text = item.libelle });
}
ViewBag.categ = selectListItems;
db.SaveChanges();
return RedirectToAction("Index");
}
}
else return View(article);
}
catch
{
return View();
}
return View();
}
//dropdown content
#Html.DropDownList("categ",(List<SelectListItem>)ViewBag.categ, "-- Select Category -- ", new { id = "subCategory" })

Dropdown selected value with ADO data model and ASP.NET MVC4

Having a hard time getting the selected value to stick on an ASP.NET MVC page.
public partial class AdjustedCost
{
public SelectList BrandList { get; set; }
public string Brand { get; set; }
}
The BrandList is getting set in the controller:
private static SelectList BrandList = new SelectList( new[] { "Brand1","Brand2","Brand3" } );
public ActionResult EditByTextbox(String textBoxEdit)
{
...
AjustedCost xadjcost = db.xAdjCost.First(e => e.InvtId == textBoxEdit);
...
xadjcost.BrandList = BrandList;
return View( "Edit", xadjcost);
}
And in the Edit view:
#Html.DropDownListFor(model => model.Brand, Model.BrandList )
Is this correct? The dropdown portion is working but the selected value is just returning the top of the list, not the actual currently set value.
You need to pass in selectedValue into the constructor of SelectList(), instead of using that static variable, which has no context to your current value from the DB.
Therefore I would create a method to give you your select list in context of the value you need selected i.e.
private SelectList BrandList(string selectedValue)
{
SelectList selectList = null;
List<SelectListItem> selectListItems = null;
try
{
selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem { Text = "Brand1", Value = "Brand1" });
selectListItems.Add(new SelectListItem { Text = "Brand2", Value = "Brand2" });
selectListItems.Add(new SelectListItem { Text = "Brand3", Value = "Brand3" });
selectList = new SelectList(selectListItems, "Value", "Text", selectedValue);
}
catch (Exception exception)
{
exception.Log(); // or whatever you do with your exceptions
}
return selectList;
}
Therefore in your action result, this:
xadjcost.BrandList = BrandList;
Becomes:
xadjcost.BrandList = BrandList(whateverTheBrandValueFromYourDbIs);

Get Enums for dropdownlist in asp.net mvc3

This is my enum
public class Woodshape
{
public enum eWoodShape
{
Round = 10,
Oval = 20,
Plain = 30
}
}
Now i want to add this as a dropdownlist in my controller
public ActionResult Create()
{
List<string> li = new List<string>();
FieldInfo[] myEnumFields = typeof(Woodshape.eWoodShape).GetFields();
foreach (FieldInfo myField in myEnumFields)
{
if (!myField.IsSpecialName && myField.Name.ToLower() != "notset")
{
int myValue = (int)myField.GetValue(0);
li.Add(myField.Name);
}
}
ViewBag.ddlEnumshape = new SelectList(myEnumFields, "myValue", "Name");
return View();
}
and In my view binded it as..
<div>
#Html.DropDownList("ddlEnumshape", "-Select shape-")
/<div>
but, it is showing error
System.Reflection.RtFieldInfo' does not contain a property with the name 'myValue'.
Could anyone help me
public static IEnumerable<SelectListItem> GetListEnumWrap<TEnum>()
{
var items = new List<SelectListItem>();
if (typeof(TEnum).IsEnum)
{
foreach (var value in Enum.GetValues(typeof(TEnum)).Cast<int>())
{
var name = Enum.GetName(typeof(TEnum), value);
name = string.Format("{0}", name);
items.Add(new SelectListItem() { Value = value.ToString(), Text = name });
}
}
return items;
}
use:
#Html.DropDownListFor(m => m.Type, EnumExtensions.GetListEnumWrap<Types>())
I use this method:
public static Dictionary<int, string> EnumToDictionary<T>()
{
return Enum.GetValues(typeof (T)).Cast<T>().ToDictionary(x => Convert.ToInt32(x), x => x.ToString());
}
ViewBag.ddlEnumshape = new SelectList(EnumToDictionary<Woodshape.eWoodShape>, "Key", "Value");

The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'?

So my code was working before. I don't know what I did for this to happen and I can't seem to fix it. I've seen people say to reset the ModelState. ( ModelState.Clear(); ) But that didn't help. Also, it doesn't help that I'm still fairly new to MVC. Any help would be appreciated. Thanks.
Controller:
public ActionResult Create()
{
ActiveDirectoryModel adm = new ActiveDirectoryModel();
ViewBag.notifyto = adm.FetchContacts();
var model = Populate();
return View(model);
}
[HttpPost]
public ActionResult Create(CreateViewModel model)
{
if (ModelState.IsValid)
{
model.leaf.Date = DateTime.Now.Date;
model.leaf.Category = model.CategoryId;
model.leaf.SubCategory = model.SubCategoryId;
model.leaf.AssignedTo = model.AssignedToId;
model.leaf.CoAssignedTo = model.CoAssignedToId;
model.leaf.Status = model.StatusId;
model.leaf.Priority = model.PriorityId;
//model.lead.Parent = model.ParentID;
db.LeafItems.AddObject(model.leaf);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
public CreateViewModel Populate()
{
ActiveDirectoryModel adm = new ActiveDirectoryModel();
var model = new CreateViewModel
{
AssignedToItems = adm.FetchContacts(),
CoAssignedToItems = adm.FetchContacts(),
NotifyToItems = adm.FetchContacts(),
CategoryItems =
from c in new IntraEntities().CategoryItems.ToList()
select new SelectListItem
{
Text = c.Name,
Value = c.ID.ToString()
},
SubCategoryItems =
from sc in new IntraEntities().SubCategoryItems.ToList()
select new SelectListItem
{
Text = sc.Name,
Value = sc.ID.ToString()
},
StatusItems =
from s in new IntraEntities().StatusItems.ToList()
where s.IsPriority == false
select new SelectListItem
{
Text = s.Name,
Value = s.ID.ToString()
},
PriorityItems =
from p in new IntraEntities().StatusItems.ToList()
where p.IsPriority == true
select new SelectListItem
{
Text = p.Name,
Value = p.ID.ToString()
}
};
return model;
}
View:
<div class="createTopInner">
<div class="editor-label">
#Html.LabelFor(model => model.leaf.Category)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.CategoryId, Model.CategoryItems, "")
#Html.ValidationMessageFor(model => model.leaf.Category)
</div>
</div>
Model:
public int CategoryId { get; set; }
public IEnumerable<SelectListItem> CategoryItems { get; set; }
If your ModelState is not valid on your POST action, you need to repopulate your SelectList properties:
if( ModelState.IsValid )
{
// save and redirect
// ...
}
// repopulate your SelectList properties:
model.CategoryItems = GetCategories();
return View(model);
Do not repopulate the entire model because otherwise you could potentially lose any changes that the user made.
another way i have find the solution is take hidden field. so in your case you could do as below:
#Html.HiddenFor(model => model.CategoryId)
Now with another field form also post and set CategoryId in respective model.

Categories