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);
Related
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
I am getting an error that I cant seem to fix:
"The ViewData item that has the key 'posts.Id' is of type
'System.Int32' but must be of type 'IEnumerable'."
ViewModel/PostViewModel
namespace MyBlogger.ViewModel
{
public class PostsViewModel
{
public Post posts { get; set; }
public IEnumerable<SelectListItem> Tags { get; set; }
private List<int> _selectedPostTags;
public List<int> SelectedPostTags
{
get
{
if (_selectedPostTags == null)
{
_selectedPostTags = posts.Tags.Select(m => m.Id).ToList();
}
return _selectedPostTags;
}
set { _selectedPostTags = value; }
}
}
}
PostController: (Manually Setting the Id for now)
public ActionResult EditPostTag(int id = 12)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var postsViewModel = new PostsViewModel
{
posts = db.Posts.Include(i => i.Tags).First(i => i.Id == id),
};
if (postsViewModel.posts == null)
return HttpNotFound();
var tagsList = db.Tags.ToList();
postsViewModel.Tags = tagsList.Select(o => new SelectListItem
{
Text = o.Name,
Value = o.Id.ToString()
});
ViewBag.UserID =
new SelectList(db.BlogUsers, "Id", "Email", postsViewModel.posts.Id);
return View(postsViewModel);
}
You have
#Html.DropDownListFor(m => m.posts.Id, (SelectList)ViewBag.Id, Model.posts.Id);
but your controller method does not assign a SelectList to a ViewBag property named Id, hence it it null in the view, which results in that exception.
You need to assign the value of ViewBag.Id to a SelectList before you return the view, although since you are using a view model, I recommend you include a property public SelectList PostsList { get; set;} in your view model and assign it to that instead and use it as
#Html.DropDownListFor(m => m.posts.Id, Model.PostsList);
Side note: Its not clear what you think the 3rd parameter (Model.posts.Id) of your current usage is doing (its for generating a null value label option)
How can i implement simple DropDownList without Id.
public AddItemModel()
{
Types = new SelectList(new []{"Type1", "Type2", "Type3"});
}
public SelectList Types { get; set; }
#Html.DropDownListFor(x => x.AddItem, ???
You will need a property on your view model to hold the selected value and then you may try this:
public AddItemModel()
{
var data = new [] { "Type1", "Type2", "Type3" };
Types = data.Select(x => new SelectListItem
{
Value = x,
Text = x,
});
}
public IEnumerable<SelectListItem> Types { get; set; }
public string SelectedType { get; set; }
and then in your view:
#Html.DropDownListFor(x => x.SelectedType, Model.Types)
I have a table in my database which I select all Mem_NA to fill it in my dropdownlist in my view.
I can't understand how can I fill the values in there? Someone can give me a hand?
My Model
public class MemberBasicData
{
public int Id { get; set; }
public string Mem_NA { get; set; }
public string Mem_Occ { get; set; }
}
public List<MemberBasicData> GetAllMembers()
{
DateTime today = DateTime.Now;
List<MemberBasicData> mbd = new List<MemberBasicData>();
using (SqlConnection con = new SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id,Mem_NA,Mem_Occ FROM Mem_Basic", con))
{
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MemberBasicData mb = new MemberBasicData();
mb.Id = (int)reader["Id"];
mb.Mem_NA = (string)reader["Mem_NA"];
mb.Mem_Occ =(string)reader["Mem_Occ"];
mbd.Add(mb);
}
}
catch (Exception e)
{
throw e;
}
finally
{
if (con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
}
return mbd;
}
}
}
GetAllMembers() function is an IEnumerable function which I was used for get all details of members. Can I use the same function for filling the dropdown list?
My controller
public ActionResult Register()
{
return View(new Member());
}
And View
#Html.DropDownListFor("-- Select --", new SelectList("")) <=== ???? i dont know
Model
public MemberModel
{
List<SelectListItem> MemberList { get; set; }
}
Controller
public ActionResult Register()
{
MemberModel model = new MemberModel();
model.MemberList = GetAllMembers()
.Select(m => new SelectListItem
{
Text = string.format("{0}, {1}", m.Mem_NA, m.Mem_Occ),
Value = m.Id
});
SelectListItem default = new SelectListItem
{
Text = "-- SELECT --",
Value = 0
};
model.MemberList.Insert(0, default);
return View(model);
}
View
#Html.DropDownList(Model.MemberList);
UPDATE: This version adds a default entry to the beginning of the list.
#Html.DropDownListFor gets an IEnumerable of SelectListItem. But instead, you want to use a list of MemberBasicData. You must convert your MemberBasicData list to SelectListItem and pass it to the #Html.DropDownListFor instead of a list of MemberBasicData. For passing related data to the Views as Sirwan pointed, you can use ViewBag or ViewData.
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.