Html.DropDownList doesn't display SelectList selected value - c#

I've read a bunch of questions about the subject but haven't managed to find a solution to this specific problem.
Controller
public ActionResult Index() {
string categorie = "--Tout--";
string souscategorie = "--Tout--";
if (Session["Categorie"] != null) {
categorie = Session["Categorie"].ToString();
}
if (Session["SousCategorie"] != null) {
souscategorie = Session["SousCategorie"].ToString();
}
SelectList cats = new SelectList(GetCategories(), categorie);
SelectList sCats = new SelectList(GetSousCategories(), souscategorie);
ViewBag.Categories = cats;
ViewBag.SousCategories = sCats;
using(DAL.WebShopEntities entities = new WebShopEntities()) {
return View(entities.Article.ToList());
}
}
View
#Html.Label("Catégories")
#Html.DropDownList("Categories", (SelectList)ViewBag.Categories, new { #class = "form-control dropdownlist" })
<br />
#Html.Label("Sous-Catégories")
#Html.DropDownList("SousCategories", (SelectList)ViewBag.SousCategories, new { #class = "form-control dropdownlist" })
When debugging the view I can see clearly that the option stocked in the session is sent to the View. But it displays the index 0 when checking in the browser. This has me bugging because the SelectList behaves normally, I think the problem lays with the DropDown but what could be the problem?

Can you try to change your Viewbag property name and try again?
try Categories => CategoriesList and
SousCategories=> SousCategoriesList
public ActionResult Index() {
string categorie = "--Tout--";
string souscategorie = "--Tout--";
if (Session["Categorie"] != null) {
categorie = Session["Categorie"].ToString();
}
if (Session["SousCategorie"] != null) {
souscategorie = Session["SousCategorie"].ToString();
}
SelectList cats = new SelectList(GetCategories(), categorie);
SelectList sCats = new SelectList(GetSousCategories(), souscategorie);
ViewBag.CategoriesList = cats;
ViewBag.SousCategoriesList = sCats;
using(DAL.WebShopEntities entities = new WebShopEntities()) {
return View(entities.Article.ToList());
}
}
#Html.Label("Catégories")
#Html.DropDownList("Categories", (SelectList)ViewBag.CategoriesList, new { #class = "form-control dropdownlist" })
<br />
#Html.Label("Sous-Catégories")
#Html.DropDownList("SousCategories", (SelectList)ViewBag.SousCategoriesList, new { #class = "form-control dropdownlist" })

Related

Concatenate between two Razor elements and save value in Database table column in the POST ActionResult

I have a static dropdownlist and editor need to take the selected value from the dropdownlist and the written value from the editor and make a concatenation between the two values and save it in a Database table column in the post ActionResult:
This is the View:
#Html.DropDownList("Term.Description", new List<SelectListItem>
{
new SelectListItem{ Text="Winter", Value = "Winter-" },
new SelectListItem{ Text="Spring", Value = "Spring-" },
new SelectListItem{ Text="Fall", Value = "Fall-" },
new SelectListItem{ Text="Summer", Value = "Summer-" }
}, new { #class = "description-text" })
#Html.Editor("TermYear","", new { htmlAttributes = new { #class = "description-text", placeholder = "2018", data_placeholder = " " } })
ActionResult:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Term term, int[] applicantTypes)
{
ModelState.Remove("ApplicantTypes");
if (ModelState.IsValid)
{
if (applicantTypes != null && applicantTypes.Length > 0)
{
foreach (var item in applicantTypes)
{
term.ApplicantTypes.Add(db.ApplicantTypes.FirstOrDefault(x => x.ApplicantTypeID == item));
}
}
db.Terms.Add(term);
db.Configuration.ValidateOnSaveEnabled = false;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ApplicantTypes = new MultiSelectList(db.ApplicantTypes, "ApplicantTypeID", "Name", term.ApplicantTypes.Select(x => x.ApplicantTypeID));
return View(term);
}
Finally, I need the `Term.Description = DropDownListSelectedValue-EditorValue'

Getting drop down city list to show after state is selected ASP MVC5

I feel like I have a working idea but I am getting a "Object reference not set to an instance of an object" error when I build the application. I am simply trying to display a drop down list for cities after the selection for state is made. I have a list of states in a seperate class that I am using for a drop down list in a form. What I am attempting to do is grab the selected state and pass it as a perameter into a different class in order to select the correct list of cities to be displayed as another drop down. So if someone selects washington state then cities such as Seattle and Tacoma show up and not cities from a different state. Here is the razor for the drop downs (the state works fine):
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.State, WebGridProject.Models.StateCodes.GetStatesList(), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.City, WebGridProject.Models.CityNames.GetStateCities(Model.State), new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
And here is the class for cities:
public class CityNames
{
public static IEnumerable<SelectListItem> GetStateCities(string stateName)
{
IList<SelectListItem> cities = new List<SelectListItem>();
switch (stateName)
{
case "AK":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Anchorage", Value = "Anchorage"},
new SelectListItem() {Text = "Fairbanks", Value = "Fairbanks"},
};
break;
case "AL":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Auburn", Value = "Auburn"},
new SelectListItem() {Text = "Birmingham", Value = "Birmingham"},
new SelectListItem() {Text = "Dothan", Value = "Dothan"},
new SelectListItem() {Text = "Mobile", Value = "Mobile"},
};
break;
case "AZ":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Pheonix", Value = "Pheonix"},
new SelectListItem() {Text = "Flagstaff", Value = "Flagstaff"},
new SelectListItem() {Text = "Prescott", Value = "Prescott"},
new SelectListItem() {Text = "Tucson", Value = "Tucson"},
};
break;
case "AR":
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Fayetteville", Value = "Fayetteville"},
new SelectListItem() {Text = "Fort smith", Value = "Fort smith"},
new SelectListItem() {Text = "Jonesboro", Value = "Jonesboro"},
new SelectListItem() {Text = "Texarkana", Value = "Texarkana"},
};
break;
default:
cities = new List<SelectListItem>
{
new SelectListItem() {Text = "", Value = ""},
new SelectListItem() {Text = "Please Select State", Value = "Please Select State"},
};
break;
}
return cities;
}
}
to me the error seemed to be pointing to there being no default value and having an issue with loading a null value. But I have a default case in the switch statement to cover this issue. I am pretty new to MVC and I will continue to work on this on my own. But if anyone has any ideas I am all ears because I am struggling to figure this out. Just FYI, the states class is also an IList<> that returns the list of state names.
request for action to be posted:
public ActionResult MyHomePage()
{
return View();
}
//Post method
[HttpPost]
public ActionResult MyHomePage(WebGridTable TWG)
{
try
{
if (ModelState.IsValid)
{
UserManager UM = new UserManager();
UM.addNewUser(TWG);
ModelState.Clear();
return View();
}
return View();
}
catch (Exception e)
{
return View("Error");
}
}
action doesnt really mean anything without the method I wrote for managing the form:
public void addNewUser(WebGridTable AddNew)
{
using (WebGridDBEntities4 db = new WebGridDBEntities4())
{
WebGridTable TWG = new WebGridTable();
TWG.Name = AddNew.Name;
TWG.DOB = AddNew.DOB;
TWG.AddressLine1 = AddNew.AddressLine1;
// TO DO: Figure out issue with accepting null value into database.
if (AddNew.AddressLine2 != null)
{
TWG.AddressLine2 = AddNew.AddressLine2;
}
else if (AddNew.AddressLine2 == null)
{
TWG.AddressLine2 = 0;
}
TWG.State = AddNew.State;
TWG.City = TWG.City;
TWG.Zip = AddNew.Zip;
TWG.Gender = AddNew.Gender;
db.WebGridTables.Add(TWG);
db.SaveChanges();
}
}
You need to use JQuery actions on Changes of the States DropDownList. Send the value to a specific Action in your Controller and Call your States.GetStatesName('Value') in that. Check the Code below. I think it would help.
$("#State").on('change',function () {
var loadingoption = $('<option></option>').text("Pleas Wait");
$('#city').attr("disabled","disabled").empty().append(loadingoption);
jQuery.getJSON("/Home/CityJson/" + $("#State > option:selected").attr("value"), function (data) {
var defaultoption = $('<option value="">Please choose a City</option>');
$('#city').removeAttr("disabled").empty().append(defaultoption);
jQuery.each(data, function (i) {
var option2 = $('<option></option>').attr("value", data[i].Name).text(data[i].Name);
$("#city").append(option2);
});
});
});
I used ActionResult "CityJson" in my HomeController. So choose your Action in getJSON.
Here is the Controller:
public ActionResult CityJson(string id)
{
var state = db.States.FirstOrDefault(x => x.Name == id);
var model = db.Cities.Where(x => x.StateId == state.Id).Select(x => new { x.Name }).ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
you can call your actions inside the Class and send them using Json.
Good Luck.

DropDownList not selected in Edit page

I Created Controller with "MVC 5 Controller with views, using Entity Framework" and modify "DropDownList" code in "Edit" view to
#Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.prdepno, new { #class = "form-control" })
in Controller use ViewBag
personal personal = db.personals.Find(id);
ViewBag.prdepno = new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);
no error ,but dropdownlist not selected
I lookup from Adding a css class to select using #Html.DropDownList()
and other question try to do that, but It not work (for me)
I don't know to do
(sorry, in my communication.)
I think you need to change the name of ViewBag Object
personal personal = db.personals.Find(id);
ViewBag.DwPrdeps= new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);
after that use ViewBag.DwPrdeps in your view
#Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.DwPrdeps, new { #class = "form-control" })
Try With this code It's Work properly
Code Generate/ Model
public class CityList
{
public string city { get; set; }
}
public static IEnumerable<SelectListItem> GetCity()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "Dhaka", Value = "dhk" },
new SelectListItem{Text = "Chittagong", Value = "CTG" }
};
return items;
}
For Create
ViewBag.city = new SelectList(GetCity(), "Text", "Value");
#Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { #class = "form-control select2", required = "required" })
For edit
ViewBag.city = new SelectList(GetCity(), "Text", "Value",model.city);
#Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { #class = "form-control select2", required = "required" })
You Can Try This it's work fine.

How can I remove the double quotes after sending data to view with ViewBag?

I have many to many relationship in edit page how can i show selected items selected in a Dropdown multi select
here is my code:
// GET: Project/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var edata = db.Projects.Find(id);
//check if data
if (edata == null)
return HttpNotFound();
//IEnumerable<SelectListItem> items = db.Provinces.Select(c => new SelectListItem { Value = c.ID.ToString(), Text = c.Name });
//ViewBag.ProvinceId = items;
//---Get all provice-----
var Prov = from c in db.Provinces select c;
//------get province ids---------------
var prov_id = from o in db.ProRel where o.ProjectId == id select o.ProvinceIds;
List<int> mid_list = new List<int>();
foreach (var p_ids in prov_id)
{
mid_list.Add(p_ids);
}
var option_vals = "";
var selected = string.Empty;
foreach (var p_itmes in Prov)
{
if (mid_list.Contains(p_itmes.ID))
{
selected = "selected='selected'";
}
else
{
selected = "";
}
option_vals += "<option "+selected+" value="+p_itmes.ID+">"+p_itmes.Name+"</option>";
}
string test = option_vals.ToString();
string test2 = test.Replace("\"", "");
ViewBag.options = test2;
return View(edata);
}
in my edit view my code:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
<select name="prov" id="prov">
#ViewBag.options
</select>
</div>
</div>
it displays the option values with double quotes at the end and it does not render like Html select options how can I remove the quotes that my options should be shown in its normal mode.
when I inspect element in browser the options are shown like this:
"<option value=1>Kabul</option><option selected='selected' value=2>Mazar</option><option selected='selected' value=3>Parwan</option><option value=4>Herat</option><option value=5>Badakhshan</option><option value=6>Takhar</option><option value=7>Smanagan</option><option selected='selected' value=8>Zabul</option>"
or you suggest me another way for this I am new to ASP.Net
I agree with #ChrFin Answer but with some more details which I hope will solve your problem
// GET: Project/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var edata = db.Projects.Find(id);
//check if data
if (edata == null)
return HttpNotFound();
//IEnumerable<SelectListItem> items = db.Provinces.Select(c => new SelectListItem { Value = c.ID.ToString(), Text = c.Name });
//ViewBag.ProvinceId = items;
//---Get all provice-----
var Prov = from c in db.Provinces select c;
//------get province ids---------------
var prov_id = from o in db.ProRel where o.ProjectId == id select o.ProvinceIds;
List<int> mid_list = new List<int>();
foreach (var p_ids in prov_id)
{
mid_list.Add(p_ids);
}
var options = new List<SelectListItem>();
foreach (var p_itmes in Prov)
{
var item = new SelectListItem();
if (mid_list.Contains(p_itmes.ID))
item.Selected = true;
item.Value = p_itmes.ID.ToString();
item.Text = p_itmes.Name;
options.Add(item);
}
ViewBag.options = options;
return View(edata);
}
and inside your view add the following extra attribute:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
#Html.DropDownList("prov", (List<SelectListItem>)ViewBag.options, htmlAttributes: new { #class = "form-control", #multiple = "multiple" })
</div>
</div>
Short answer was already given by Marcos via his comment, but in general thats not how you create a select tag within MVC 5:
Controller:
public ActionResult Edit(int? id)
{
// other code
var options = new List<SelectListItem>();
foreach (var p_itmes in Prov)
{
var item = new SelectListItem();
if (mid_list.Contains(p_itmes.ID))
item.Selected = true;
item.Value = p_itmes.ID.ToString();
item.Text = p_itmes.Name;
options.Add(item);
}
ViewBag.options = options;
return View(edata);
}
View:
<div class="form-group">
<label class="control-label col-md-2">Provinces</label>
<div class="col-md-10">
#Html.DropDownList("prov", (List<SelectListItem>)ViewBag.options,
htmlAttributes: new { multiple = "multiple" })
</div>
</div>

How to bind value to dropdownlist in asp.net mvc?

I have several textboxes and one dropdownlist like:
for (int i = 0; i < count; i++)
{
<tr>
<td>#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, (SelectList)ViewBag.ProjectList, "-- Choose a Project --", new { #id = "ddlProjectvalue" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SUN_HRS, new { style = "width:50px; height:30px;", #class = "sunhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].MON_HRS, new { style = "width:50px; height:30px;", #class = "monhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].TUE_HRS, new { style = "width:50px; height:30px;", #class = "tuehrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].WED_HRS, new { style = "width:50px; height:30px;", #class = "wedhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].THU_HRS, new { style = "width:50px; height:30px;", #class = "thurhrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].FRI_HRS, new { style = "width:50px; height:30px;", #class = "frihrs" })
</td>
<td>#Html.TextBoxFor(m => m.GetTimeSheetDetails[i].SAT_HRS, new { style = "width:50px; height:30px;", #class = "sathrs" })
</td>
</tr>
</td>
}
and I want to bind data from database to all the fields , every thing is displaying data perfectly, but dropdown list for proj_id is not showing text even though i am passing value to dropdownlist. i am passing like :
public int GetTimsheetData(int empid, TimesheetModel TimesheetModel)
{
// GetimeSheet all the rows according employee name
var emps = (from n in db.TIMESHEETs
where n.RES_ID == empid
select n).ToList();
int count = emps.Count();
HttpContext.Current.Session["count"] = count;
try
{
List<TimesheetModel> emptyList = new List<TimesheetModel>();
TimesheetModel.GetTimeSheetDetails = emptyList; //taking Empty List and bind to GetTimesheetDetails for Add items into it.
//if Employee Name has more than one record.
if (emps.Count() > 0)
{
foreach (var timeSheet in emps)
{
TimesheetModel item = new TimesheetModel();
item.WEEK_CAL_ID = timeSheet.WEEK_CAL_ID;
item.PROJ_ID = timeSheet.PROJ_ID;
item.SUN_HRS = timeSheet.SUN_HRS;
item.MON_HRS = timeSheet.MON_HRS;
item.TUE_HRS = timeSheet.TUE_HRS;
item.WED_HRS = timeSheet.WED_HRS;
item.THU_HRS = timeSheet.THU_HRS;
item.FRI_HRS = timeSheet.FRI_HRS;
item.SAT_HRS = timeSheet.SAT_HRS;
TimesheetModel.GetTimeSheetDetails.Add(item);
}
}
}
catch (Exception ex)
{
throw ex;
}
return count;
}
and returning to controller like :
public ActionResult GetEmployeeDetails(int empId, string btn, TimesheetModel timesheetModel)
{
Employer_BL employerBL = new Employer_BL();
ViewBag.ProjectList = timesheetModel.getProjects;
//If GetTimesheetData returns morethan one record
if (employerBL.GetTimsheetData(empId, timesheetModel) >= 0)
{
timesheetModel.EMP_ID = empId;
//passes model data to View
return View("Timesheet", timesheetModel);
}
TimesheetModel model = new TimesheetModel();
model.EMP_ID = empId;
return View("Timesheet", model);
}
Where am I doing wrong, dropdownlist showing initial index instead of showing text of passing values. Please help me anyone.
in Separate Class I have written like below to get project names:
public SelectList getProjects()
{
IEnumerable<SelectListItem> projectslist = (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() });
return new SelectList(projectslist, "Value", "Text", PROJ_ID);
}
It depends on the ViewBag.ProjectList which I cannot found on your source code. You could populate it with an object of type IEnumerable<SelectListItem> with one of the item Selected properties set to true.
public IEnumerable<SelectListItem> GetList()
{
return (from proj in res.PROJECTs where proj.IS_DELETED == "N" select proj).AsEnumerable().Select(projt => new SelectListItem() { Text = projt.NAME, Value = projt.ID.ToString() }).ToList();
}
on your controller
ViewBag.ProjectList = GetList();
on your view
#{
var projectList =
new SelectList(ViewBag.ProjectList, "Value", "Text", Model.GetTimeSheetDetails[i].PROJ_ID.ToString())
}
#Html.DropDownListFor(m => m.GetTimeSheetDetails[i].PROJ_ID, projectList, "-- Choose a Project --")
You can try like this method:
[NonAction]
private IEnumerable<SelectListItem> GetData()
{
return new List<SelectListItem>()
{
new SelectListItem(){ Text="--Select--", Value="0"},
new SelectListItem(){ Text="A", Value="1"},
new SelectListItem(){ Text="B", Value="2"},
new SelectListItem(){ Text="C", Value="3"},
};
}
Call this function in Action Method
public ActionResult Create()
{
ViewData["categories"] = GetData();
return View();
}
On your html page:
<%= Html.DropDownList("cat", (IEnumerable<SelectListItem>)ViewData["categories"])%>
You can use viewbag . in your controller you can read your data from the database :
public ActionResult Create()
{
ViewBag.ClassName = new SelectList(objclassrep.GetClasslist(), "Id", "ClassName");
}
And in your view model you can read the data from controller like this :
<div class="editor-label">
#Html.LabelFor(model => model.ClassId)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ClassId, (SelectList)ViewBag.ClassName);
#Html.ValidationMessageFor(model => model.ClassId)
</div>
This code automatically binds ids of your data to DDL Here is class id.
This is th getClassList function :
public List<Class> GetClasslist()
{
return _dbcontext.Classes.ToList();
}

Categories