get selectlist text - asp.net

when i bind my select list to a dropdownlist in a view i see where i can get the selected value (but in my case, it's a number). is there a way i can get the description/text from the select list?

Here is one way:
$(function() {
$('select').change(function() {
alert($('select option:selected').text());
});
});
<select>
<option value="0">Zero</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Working jsfiddle: http://jsfiddle.net/wherC/
If you have multiple select elements on a page you will need to change the selector accordingly.

The the value of the selected option is what will be transferred as the form key of a select list.
Example
<select name="list1">
<option selected value="1">one</option>
</select>
will produce a key list1=1
If you need the description, bind the description to the value of the select list.
<select name="list1">
<option selected value="one">one</option>
</select>
will produce a key list1=one
If you are using SelectListItem this option would be:
new SelectListItem {
Text = "one",
Value = "one"
}

Not sure if I understand your question but :
Assuming our collection we want to use for populating our dropdown list is made from :
public class Animal
{
public int ID { get; set; }
public string Name { get; set; }
}
Then you can populating your list would be
#Html.DropDownListFor(model => model.AnimalId, new SelectList(AnimalList, "ID", "Name"))
For the sample above ID is the "Value" and Name would be displayed as option to choose. If you want it the other way around - just replace names of the class properties/fields
If you want both ID and Name to be displayed on the dropdown list to produce
<option value="1">1 - Horse</option>
I would go with
#Html.EditorFor(model => model.id, "PickAnimalTemplate", new { animals = ViewBag.Animals})
which is defining custom EditorTemplate for this property, where you can pretty much do whatever you want with the layout for example :
#foreach (var item in animals)
{
<option value="#item.ID">#item.ID - #item.Name</option>
}

Related

Razor pages entire model object as a option value from view to controller

I am looking for a way to pass currently selected model from view to controller.
My select code:
<select asp-for="Product">
#foreach (var p in Model.Products)
{
<option value="#p">#p.ProductName</option>
}
</select>
I'm trying to bind option value #p to bind with my property below:
[BindProperty]
public Product Product { get; set;}
But whenever after submitting my form the Product property has "null" values.
Any suggestions?
I think you can use a hidden type for this. No need to query to find ProductName after submit in list.
<input type="hidden" asp-for="ProductName" />
<select asp-for="ProductId">
#foreach (var p in Model.Products)
{
<option value="#p.Id">#p.ProductName</option>
}
</select>
<script>
$(function () {
$('form').submit(function () {
var productName = $('#ProductId option:selected').text();
$('#ProductName').val(productName);
});
});
</script>
Usually you would pass the Id of the selected item when the form is posted. That is typically enough data to work with. However, if you really want the ModelBinder to create a Product instance from the posted values, your form fields should be named Product.ProductId and Product.ProductName. The other answer shows how to obtain the ProductName value and then assign it to a hidden field.
<select asp-for-"Product.ProductId" asp-items="Model.Products">
...
</select>
<input type="hidden" asp-for="Product.ProductName" />

How to populate dropdown in thymeleaf with hashmap set from controller

I want the dropdown in the view to be get filled with value set from the controller. In my controller using model attribute I have added the list limits
#RequestMapping(value = "/works", method = RequestMethod.GET)
public String searchWorks(Model model){
Map< Integer, String > limits = new HashMap<Integer, String>();
limits.put(20, "20件");
limits.put(25, "25件");
limits.put(30, "30件");
limits.put(35, "35件");
limits.put(40, "40件");
limits.put(45, "45件");
limits.put(50, "50件");
model.addAttribute("limits",limits);
model.addAttribute("limit",limit);
return "workSituation";
}
In view Page in order to populate the dropdown with the value set using model attribute I have used this code
<div class="col-sm-3">
<select class="form-control" name = "limit" id="limit" onchange="getList(this.value)">
<option selected>-- select number of items--</option>
<option data-th-each="limit : ${limits}"
data-th-value="${limt.getKey()}"
data-th-text="${limt.getValue()}" >
</select>
</div>
I am getting the error
caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "limt.getKey()"
caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "limt.getValue()"
What will be the cause for this. Actually dropdown is iterating 7 times(the number of records in the limits list) but the key and value is not able to fetch with code.What is the correct way to get the dropdown filled with
<option value="20">20件</option>
<option value="25">25件</option>
<option value="30">30件</option>
<option value="35">35件</option>
<option value="40">40件</option>
<option value="45">45件</option>
<option value="50">50件</option>
For thymeleaf try the following
<option th:each="limit : ${limits.entrySet()}" th:value="${limit.key}" th:text="${limit.value}"></option>

Angularjs 1.2 adds empty option in select

I have a dropdown that gets its items from database. The default value to be selected in this dropdown is retrieved from a cookie.
The problem is,
1. there is an empty option tag as the first option and also,
2. the default value is not selected.
There is no issue at all when I use v1.3.16. This happens when using v1.2.0. (I have to use only v1.2.0)
How to fix this.
ASPX:
<select id="ddlItems" data-ng-model="ItemId">
<option value="-1">-- All Circles --</option>
<option data-ng-repeat="item in Items" value="{{item.AreaCode}}"
data-ng-selected="item.AreaCode==ItemId">{{item.AreaName}}</option>
</select>
Ctrl.js:
var promise = MyFactory.GetItems();
promise.then(function (success) {
if (success.data != null && success.data != '') {
var data = success.data;
$scope.Items = data.lstItems; //bind items to dropdown
$scope.ItemId = itemIdFromCookie; //select default value
alert(itemIdFromCookie); //it pops -1
}
else {
console.log(success.data);
}
}
Rendered HTML:
<select id="ddlItems" data-ng-model="ItemId">
<option value="? string:"-1" ?"></option>
<option value="-1">-- All Circles --</option>
//...other options
</select>
Try to use ngOptions instead
Like this
<select id="ddlItems"
data-ng-model="ItemId"
ng-options="item.AreaCode as item.AreaName for item in Items">
<option value="-1">-- All Circles --</option>
</select>
This happens becausedata-ng-model="ItemId" is empty when your model is App is Loaded.
To Have some initial value. you can put default value in ng-init
For Ex : data-ng-init='data-ng-model="--SELECT--";'
Or per your Array list Item which you are getting from database set one of the values.
Remember init will get triggered b/f you complete the Ajax Call.

Edit doesn't work with Html.DropDownList and #class attribute

Controller:
ViewBag.Category = new SelectList(this.service.GetAllCategories(), product.Category);
I'm not using Id + Name. GetAllCategories() returns only several int numbers.
When I use in a View:
#Html.DropDownList("Category", String.Empty)
everything works. Edit is ok and DropDownList shows the selected value.
HTML result:
<select id="Category" name="Category">
<option value=""></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option selected="selected">5</option>
...
</select>
But I need to use css #class so I use this code:
#Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewBag.Category, new { #class = "anything" })
HTML result:
<select class="anything" id="Category" name="Category">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
...
</select>
Unfortunately, Edit still works (I can save the value that I select) but DropDownList starts to show the default value not the value saved in the database.
Do you have any ideas what would be the problem?
Update
I made an update to be more precise.
The method GetAllCategories looks like this:
public List<int> GetAllCategories()
{
List<int> categories = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
return categories;
}
The Html.DropDownList works quite interesting:
If you don't provide a selection list
#Html.DropDownList("Category", String.Empty)
it will look up the values for the selection from ViewData/ViewBag based on the provided property name: Category.
But if you provide a selection list it will look for default selected item in the ViewData/ViewBag based on the provided property name Category which of course will contain the list instead of the default value. To fix this you have two options:
Don't provide the selection list:
#Html.DropDownList("Category", null, new { #class = "anything" })
Or
Use a different name instead of the ViewBag property name Category:
#Html.DropDownList("CategoryDD", (IEnumerable<SelectListItem>)ViewBag.Category, new { #class = "anything" })
SelectList typelist = new SelectList(this.service.GetAllCategories(), "ProductID", "ProductName", product.Category);
ViewBag.Category=typelist;
I think from your table you have to suply the default values "ProductID" and text "ProductName" or the one you use and want to display so the list can be generated for this results.
Not sure what exactly your problem is but you may try this maybe it will solve it.
You can use the drop down list for html helper. Note, that the "model" you are expecting is required in the view.
#Html.DropDownListFor(model => model.savedID,
(IEnumerable<SelectListItem>)ViewBag.Category, new { #class = "anything" })

how to get the string from dropdown list

I have this code in my controller for Index view..
public ActionResult Index(int? id)
{
_viewModel.ServiceTypeListAll = new SelectList(_bvRepository.GetAllServiceTypes().ToList().OrderBy(n => n.ServiceTypeName).ToList(), "ServiceTypeId", "ServiceTypeName");
return View(_viewModel);
}
Using this I am able to dispaly all the ServiceTypes in my view in dropdownlist box. the code is
<%=Html.DropDownList("ServiceTypeListAll", new SelectList(Model.ServiceTypeListAll,"Value","Text"))%>
When I am trying to get the Selected Dropdownlist value from View to controller I am acceesing like this..
string categoryName = collection["ServiceTypeListAll"]; // collectoin refers FormCollection
I am expecting CategoryName should be string like what ever I am showing in Dropdownlist box.
I am getting Integer values?
is that somethign I am doing wrong
thanks
The value of a dropdownlist is its ID property, which you're specifying as ServiceTypeId.
You need to specify the ID as ServiceTypeName instead, like this:
_viewModel.ServiceTypeListAll = new SelectList(_bvRepository.GetAllServiceTypes().OrderBy(n => n.ServiceTypeName), "ServiceTypeName", "ServiceTypeName");
Also, Model.ServiceTypeListAll is already a SelectList; you don't need to wrap it:
<%=Html.DropDownList("ServiceTypeListAll", Model.ServiceTypeListAll)%>
This is what a select box looks like in HTML
<select>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
So the value you get in your controller is the selected value from the select box, and this is a number.
If you want to use the items text then there are two possibilities:
1) set the value of the options to the value of the text
public ActionResult Index(int? id)
{
_viewModel.ServiceTypeListAll = new SelectList(_bvRepository.GetAllServiceTypes().ToList().OrderBy(n => n.ServiceTypeName).ToList(), "ServiceTypeId", "ServiceTypeId");
return View(_viewModel);
}
2) after getting the int value load the appropriate object from your repository
int categoryId = Convert.ToInt32(collection["ServiceTypeListAll"]);
string categoryName = _bvRepository.Get(categoryId); // or whatever method loads your object
Your call to Html.DropDownList() will produce html that looks like this:
<select name="ServiceTypeListAll">
<option value="1">Service Type 1</option>
<option value="2">Service Type 2</option>
<option value="3">Service Type 3</option>
</select>
The value attribute is for whichever option is selected is what will appear in the FormCollection. If you really want the ServiceTypeName string instead of the ServiceTypeId, you can modify your SelectList constructor like this:
_viewModel.ServiceTypeListAll = new SelectList(_bvRepository.GetAllServiceTypes().ToList().OrderBy(n => n.ServiceTypeName).ToList(), "ServiceTypeName", "ServiceTypeName");
in order to produce html that looks like this:
<select name="ServiceTypeListAll">
<option value="Service Type 1">Service Type 1</option>
<option value="Service Type 2">Service Type 2</option>
<option value="Service Type 3">Service Type 3</option>
</select>
Also, incidentally, you should be able to simplify you HtmlHelper call to this:
<%=Html.DropDownList("ServiceTypeListAll", Model.ServiceTypeListAll)%>
No need to create another SelectList ...

Resources