MVC - Show list of strings in DropDownList - c#

Based on this code (auto-generated Control/View code from Visual Studio):
<div class="form-group">
#Html.LabelFor(model => model.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*Comment: Want to replace EditorFor to DropDownList("Banana, "Apple", "Orange"*#
#Html.EditorFor(model => model.Type, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
I would like to add something similar like:
#Html.DropDownList("UserId", null, htmlAttributes: new { #class = "form-control" })
(also auto-generated code, but for UserId) instead of #html.EditorFor...
I was able to see list of UserName(value = Id) from db via Controller:
ViewBag.UserId = new SelectList(db.Users, "Id", "UserName", Test.UserId);
Now, I don't want that ViewBag read from database, instead I want it to list 3 different strings that I will use to let user to chose for indata(meaning, limit them to choice one of these 3 string instead writing it).
Strings I want it to list:
"Banana"
"Apple"
"Orange"
How do I do that?

Try this,
#Html.DropDownList("DropDown", new List<SelectListItem>
{ new SelectListItem { Text = "Banana", Value = "1", Selected=true},
new SelectListItem { Text = "Apple", Value = "2"},
new SelectListItem { Text = "Orange", Value = "3"}
}, "Select Fruit")
OR
Get value in model
#Html.DropDownListFor(x => x.Id, new List<SelectListItem>
{ new SelectListItem { Text = "Banana", Value = "1", Selected=true},
new SelectListItem { Text = "Apple", Value = "2"},
new SelectListItem { Text = "Orange", Value = "3"}
}, "Select Fruit")

Simply change what you are assigning to ViewBag.UserId f.e. like this:
var fruits = new List<string> { "Banana", "Apple", "Orange" };
ViewBag.Fruits = fruits.Select(f => new SelectListItem { Text = f, Value = f });

This is how you can build your list items:
ViewBag.Fruits = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Banana", Value = 0},
new SelectListItem { Selected = false, Text = "Apple", Value = 1},
}, "Value" , "Text", 1);

Here is another way of doing it using enum
public enum Fruit { Banana, Apple, Orange }
#Html.DropDownList("FruitSelection",
new SelectList(Enum.GetValues(typeof(Fruit))),
"Select Fruit",
new { #class = "form-control" })

MVC Controler
ViewBag.PageSort = new List <SelectListItem> ()
{
new SelectListItem () {Value = "1", Text = "Discounts"},
new SelectListItem () {Value = "2", Text = "New Items"},
new SelectListItem () {Value = "3", Text = "Lowest Price"},
new SelectListItem () {Value = "4", Text = "Highest Price"}
};
in View
#Html.DropDownList("PageSort", ViewBag.PageSortas SelectList, "- Select Sort -", new { #id = "SortID", #name = "SortID", #class = "form-control" })

Related

How to set default value "0" to text "Select" in DropDownList in MVC?

Below is the dropdownlist of Country. I want selected text "Select" which is working.
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
new { #class = "form-control" })
Now I want to set the value "0" for text "Select" which is by default selected. Currently the value for "Select" is blank as shown below.
How can I do this? The value "Select" is not in the data source. I have to access this selected value in JQuery.
I have tried with these two but none of those are working.
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { #class = "form-control", #selected = "0" })
And
#Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { #class = "form-control", #selected = "0" })
Below is the controller code for CountryName values
ViewBag.CountryName = dbLMS.CountryMasters.Select(c => new { c.CountryId, c.CountryName }).OrderBy(c => c.CountryName).ToList();
You can do as follows:
Option-1:
#{
var countrySelectList = new SelectList(ViewBag.CountryName, "CountryId", "CountryName");
List<SelectListItem> countrySelectListItems = countrySelectList.ToList();
countrySelectListItems.Insert(0, (new SelectListItem { Text = "Please select", Value = "0", Selected = true }));
}
#Html.DropDownList("ddlCountryName", countrySelectListItems , new { #class = "form-control" })
Option-2:
In the controller method:
List<SelectListItem> selectListItems = dbLMS.CountryMasters.Select(a => new SelectListItem()
{
Text = a.CountryName,
Value = a.CountryId
}).ToList();
selectListItems.Insert(0, new SelectListItem(){Text = "Selet Country", Value = "0", Selected = true});
ViewBag.CountrySelectList = selectListItems;
Then in the view:
#Html.DropDownList("ddlCountryName", (List<SelectListItem>)ViewBag.CountrySelectList, new { #class = "form-control" })
new SelectList(ViewBag.CountryName, "CountryId", "CountryName", //Default value)
You dont really need a value for Select. For the model, keep the Required validation attribute.
This will ensure the value is selected. This way you dont have to check in the backend.

How to get value from Drodownlist in C#

GetCurrency(countrydetials.Country) gives me currency of that specific country. But in my scenario, I only have two currencies in my Currency dropdownlist. If the country matches currency is not available in currency dropdownlist then by default it should select Indian Rupee.
Controller code
CountryDetials countrydetials = new CountryDetials();
var model = GetCurrency(countrydetials.Country);
countrydetials.Currency = model.FirstOrDefault().Currency;
View
#Html.DropDownListFor(m => m.Currency, new List<SelectListItem>
{
new SelectListItem {Value = "INR", Text="Indian Rupee" },
new SelectListItem {Value = "NPR", Text = "Nepalese Rupee" },
},
new { #class = "form-control" })
#Html.DropDownListFor(m => m.Country, new List<SelectListItem>
{
new SelectListItem {Value = "IND", Text = "India" },
new SelectListItem {Value = "NEP", Text = "Nepal" },
new SelectListItem {Value = "SIN", Text = "Singapore" },
new SelectListItem {Value = "USA", Text = "USA" },
},
new { #class = "form-control"})

Dynamically create multiple textbox from dropdownlist entry

I am trying to create multiple textbox from dropdownlist value in C#. Below is my code. whenever I am selecting a value in dropdown list its not showing any textbox. Thanks in advance
<div class="form-group2">
#Html.LabelFor(m => m.AdditionalGuest, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.AdditionalGuest, new List < SelectListItem >{
new SelectListItem { Text = "0", Value = "0" },
new SelectListItem { Text = "1", Value = "1" },
new SelectListItem { Text = "2", Value = "2" },
new SelectListItem { Text = "3", Value = "3" },
new SelectListItem { Text = "4", Value = "4" },
new SelectListItem { Text = "5", Value = "5" }
}, new { #id = "guests" })
</div>
</div>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js">
$("#guests").change(function(){
for(i=0;i<parseInt($(this).val();i++){
$('.form-group2').append('<div class="form-group"><br>#Html.LabelFor(m => m.AdditionalGuestName, new { #class = "col-md-2 control-label" })<br><div class="col-md-10"><br>#Html.TextBoxFor(m => m.AdditionalGuestName, new { #class = "form-control" })</div></div>');
}
}
</script>
#saikat check the below solution
<div class="form-group2">
#Html.LabelFor(m => m.AdditionalGuest, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.AdditionalGuest, new List<SelectListItem>{
new SelectListItem { Text = "0", Value = "0" },
new SelectListItem { Text = "1", Value = "1" },
new SelectListItem { Text = "2", Value = "2" },
new SelectListItem { Text = "3", Value = "3" },
new SelectListItem { Text = "4", Value = "4" },
new SelectListItem { Text = "5", Value = "5" }
}, new { #id = "guests" })
</div>
</div>
<br/>
<div class="form-group3">
</div>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$("#guests").change(function () {
$('.form-group3').html("");
for (i = 0; i < parseInt($(this).val()) ; i++) {
$('.form-group3').append('<div class="form-group"><br>#Html.LabelFor(m => m.AdditionalGuestName, new { #class = "col-md-2 control-label" })#Html.TextBoxFor(m => m.AdditionalGuestName, new { #class = "form-control" })</div>');
}
});
</script>
There is a problem with your script.

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.

How to selected value true in dropdownlist MVC

i have problem in dropdownlist selected value.
View
#Html.DropDownList("QuestionType", (IEnumerable<SelectListItem>)ViewData["questiontype"], new { id = "QuestionType", #style = "max-width: 200px;width: 200px", #OnChange = "HideForm(this)", #class = "form-control" })
Controller
var questionTypeList = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "Automatic", Selected = false },
new SelectListItem { Value = "2", Text = "Custom", Selected = true}
}, "Value", "Text"
).ToList();
var questionType = new SelectList(questionTypeList, "Value", "Text");
ViewData["questiontype"] = questionType;
i want value=2 is selected true in view but my script above is not working, how can i solve this problem?
i have modified my code. i'm not using stronglytype which bind to dropdownlist. i'm using viewdata. this is my code:
Controller
List<SelectListItem> questionTypeList = new List<SelectListItem>();
questionTypeList.Add(new SelectListItem() { Text = "Automatic", Value = "1" });
questionTypeList.Add(new SelectListItem() { Selected = true, Text = "Custom", Value = "2" });
ViewData["questiontype"] = questionTypeList;
View
#Html.DropDownList("QuestionType", ViewData["questiontype"] as SelectList, new { id = "QuestionType", #style = "max-width: 200px;width: 200px", #OnChange = "HideForm(this)", #class = "form-control" })
why this code work and why previous code not work? i'm so confuse...
Not sure if you have a strongly typed view but you can use
DropdownlistFor(model=>model.QuestionType, selectlistItem)
then in your controller set
model.QuestionType to 2;
then
return View(model);

Categories