DropDownListFor not showing current value MVC - c#

I have a drop down list, but I cannot get to show the current status in the view:
My html:
<div class="form-group">
#Html.LabelFor(model => parts.Status, new { #class = "col-md-4" })
//This shows the status as "New - Dispatch"
#Html.TextBoxFor(model => parts.Status, new { #class = "col-md-8 required-color" })
//This shows as empty , but i want it to show as New - Dispatch
#Html.DropDownListFor(model => parts.Status, parts.StatusList, String.Empty, new { #class = "col-md-8 required-color" })
</div>
I'm getting my data from here:
StatusList = _partsRequestHServices.GetStatusList(parts.PartRequestStatus)
This is my List:
public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
List<SelectListItem> list = new System.Collections.Generic.List<SelectListItem>();
list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch"});
list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse"});
list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim" });
return list;
}
I want to show the current status in the view it works in the TextBoxFor, but not in the DropDownListFor.

Remove Selected = false from your SelectListItems (by using Selected = false, you are explicitly saying that you don't want any of them to be selected):
public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
List<SelectListItem> list = new System.Collections.Generic.List<SelectListItem>();
list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch" });
list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse" });
list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim" });
return list;
}

You need to return a SelectList not a generic List<SelectListItem>(). By returning this kind of list you have the opportunity to set the value of the selected item. Like this:
public List<SelectListItem> GetStatusList(string PartRequestStatus)
{
list.Add(new SelectListItem() { Text = "New - Dispatch", Value = "New - Dispatch", Selected = false });
list.Add(new SelectListItem() { Text = "Exception - Warehouse", Value = "Exception - Warehouse", Selected = false });
list.Add(new SelectListItem() { Text = "HP Claim", Value = "HP Claim", Selected = false });
}
Then consume that like this:
var statuses = GetStatusList("??");
SelectList statusList = new SelectList(statuses , "Id", "Text", selectedValue);
ViewData["Statuses"] = statusList;
Once you have this set up if you are using a custom template for your drop down list make sure your view model property for Status has this attribute:
[UIHint("string-name-of-editor-template")]

Related

Set a selected value by default in List SelectList

I want to set a selected value in my select list by default.
Here I have this select list :
#{
List
<SelectListItem>
dateEcheancierCc = new List
<SelectListItem>
();
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
}
<div class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche", dateEcheancierCc, new { #class = "form-conrol" })
</div>
}
Here I'am trying to set "Selected-value-by-default" is selected by default but it is not working for me why ?
Here the Dropdownlist:
#Html.DropDownList("DateEche", dateEcheancierCc, new { #class = "form-conrol" })
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
change to like this
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
make sure the item that you set "Selected = true" is the only one in list
I don't know your rule but you can try like this
for example : I have an array { "Jeffrey", "John", "Joe", "Josh" }, and I want set Jeffrey as default selected
if (dateEch == "Jeffrey")
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
else
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch });
Replace your DropdownList as below,
<div class="md-select px-0" style="min-width:0px">
#Html.DropDownList("DateEche",new SelectList(dateEcheancierCc,"Value","Text","Selected-value-by-default"), new { #class = "form-conrol" })
</div>
and selectList as
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(
new SelectListItem() { Text = dateEch, Value = dateEch }
);
}
https://dotnetfiddle.net/RFgoD1
if your views have model then you can use like this
#Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.SelectCollections, "Value", "Text", Model.ValueToBeSelectedInCollection))
You need to add Selected=true while building the SelectListItem.
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch ,Selected = true });
}

set value of dropdownlist based on value from database in asp.net mvc5

I have declared a SelectListItem object in my controller, I able to populate them into my DropDownList in Create() page, however I am having problem trying to get value from model to set the selected value of the DropDownList in Edit() page.
Code of Create() in controller:
public ActionResult Create()
{
var tagList = new List<SelectListItem>();
tagList.Add(new SelectListItem() { Text = "Classic", Value = "Classic" });
tagList.Add(new SelectListItem() { Text = "Promo", Value = "Promo" });
tagList.Add(new SelectListItem() { Text = "Limited", Value = "Limited" });
tagList.Add(new SelectListItem() { Text = "Classic", Value = "Classic" });
tagList.Add(new SelectListItem() { Text = "New", Value = "New" });
var catList = new List<SelectListItem>();
catList.Add(new SelectListItem() { Text = "Men", Value = "Men" });
catList.Add(new SelectListItem() { Text = "Women", Value = "Women" });
catList.Add(new SelectListItem() { Text = "Sport", Value = "Sport" });
catList.Add(new SelectListItem() { Text = "Casual", Value = "Casual" });
var statusList = new List<SelectListItem>();
statusList.Add(new SelectListItem() { Text = "Available", Value = "Available" });
statusList.Add(new SelectListItem() { Text = "Unavailable", Value = "Unavailable" });
ViewBag.tagDropDown = tagList;
ViewBag.catDropDown = catList;
ViewBag.statusDropDown = statusList;
return View();
}
I am able to populate the DropDownList in Create() view page using all the Viewbag(s).
However now I wished to populate the DropDownList in Edit() view page at the same time set selected value from the model.
Below are the codes from Edit() view page:
<div class="form-group">
#Html.LabelFor(model => model.category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.category, new SelectList(ViewBag.catDropDown, "value", "text"), htmlAttributes: new { #class = "form-control" })
</div>
</div>
All you need to do is to set the category property value of your view model object in your Edit action method.
public ActionResult Edit(int id)
{
var vm=new YourViewModel();
vm.category="Sport"; // Replace this hard coded value with value from db
// to do : Load ViewBag.catDropDown
return View(vm);
}
Now the DropDownListFor helper method will make the option "Sport" selected, assuming your view is strongly typed to YourViewModel

Is it possible to add hardcoded option/values in dropdownlist while retrieving a list from database ? MVC 5

I have this code that can retrieve a list from database in dropdownlist. I want to add hardcoded value or option to this.
Controller:
IEnumerable<SelectListItem> items = db.specimentype.Where(model => model.recordstatus == "active").ToList().Select(c => new SelectListItem
{
Value = c.code.ToString(),
Text = c.specimenType
});
ViewBag.specimentypelist = items;
View:
#Html.DropDownListFor(model => model.SpecimenType, new SelectList(ViewBag.specimentypelist, "Value", "Text", Model.SpecimenType), new { #class = "specimendropdown", #style = "height:27px; margin-left: 40px;" })
I want this to be
#Html.DropDownListFor(model => model.SpecimenType, new List<SelectListItem> { Text = "Horizontal", Value = "Horizontal" }, new SelectList(ViewBag.specimentypelist, "Value", "Text", Model.SpecimenType), new { #class = "specimendropdown", #style = "height:27px; margin-left: 40px;" })
You should move your list generation to the controller, like so for instance
model.SelectListOptions= new List<SelectListItem>
{ new SelectListItem() { Text = "DatabaseOption1", Selected = true, Value = "1"}
, new SelectListItem() { Text = "DatabaseOption2", Selected = false, Value = "2"}
, new SelectListItem() { Text = "AddedOption1", Selected = false, Value = "3"} };
And in your view, you can now reference it like so:
#Html.DropDownListFor(x => x.SpecimenType, Model.SelectListOptions, null, new { #class = "specimendropdown", #style = "height:27px; margin-left: 40px;", #disabled = "disabled" })
UPDATE
To account for your database retrieval, there's not much you need to do. You could add the SelectListItems to the list, like so:
IEnumerable<SelectListItem> items = db.specimentype.Where(model => model.recordstatus == "active").ToList().Select(c => new SelectListItem
{
Value = c.code.ToString(),
Text = c.specimenType
}).ToList();
items.Add(new SelectListItem() { Text = "AddedOption1", Selected = false, Value = "3"});
ViewBag.specimentypelist = items;
Just convert the IEnumerable to a List, and use the Add() method to append your options to the list you retrieve from the database.
You can also use the Insert method if you want to put them in at a specific place.

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.

ASP.NET MVC Dropdown List From SelectList

I am building the following SelectList in my controller.
var u = new NewUser();
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
});
return u;
And displaying it on my view like this:
#Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions)
It looks like I am giving it a valid set of SelectListItems in what should be a pretty straightforward dropdown list, but instead of getting a valid <option> list with good values and text, I get this:
<select data-val="true" data-val-range="A user type must be selected." data-val-range-max="2" data-val-range-min="1" data-val-required="The UserType field is required." id="UserType" name="UserType" class="input-validation-error">
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
<option>System.Web.Mvc.SelectListItem</option>
</select>
What gives? As far as I can tell, this should work.
You are missing setting the Text and Value field in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text", 1);
BTW, you can use a list or array of any type... and then just set the name of the properties that will act as Text and Value.
I think it is better to do it like this:
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text");
I removed the -1 item, and the setting of each item selected true/false.
Then, in your view:
#Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")
This way, if you set the "Select one" item and don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).
If you need to set one of the SelectList items as selected, you can use:
u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);
As one of the users explained in the comments:
The 4th option of the SelectList constructor is ignored when binding to a property using DropDownListFor() - it is the property's value that determines what is selected.
Just try this in razor
#{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Google", Value = "Google"},
new SelectListItem {Text = "Other", Value = "Other"},
}, "Value", "Text");
}
and then
#Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { #class = "css-class" })
or
#Html.DropDownList("ddlDropDownList", selectList, "Default label", new { #class = "css-class" })
Try this, just an example:
u.UserTypeOptions = new SelectList(new[]
{
new { ID="1", Name="name1" },
new { ID="2", Name="name2" },
new { ID="3", Name="name3" },
}, "ID", "Name", 1);
Or
u.UserTypeOptions = new SelectList(new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
},"Value","Text");
var selectList = new List<SelectListItem>();
selectList.Add(new SelectListItem {Text = "Google", Value = "Google"}) ;
selectList.Add(new SelectListItem {Text = "Other", Value = "Other"}) ;

Categories