Reputation: 4122
I'm trying to update Textbox's with the selected items info(properties). Can I get the selected Items Name instead of the Id, or in other words how can I get the properties of whats in my ViewData in the javascript upon selecting an item and then set it to a txtbox?
@Html.ListBox("ListBoxName", new SelectList((IEnumerable<Epic>)ViewData["selectedestimate"], "Id", "Name", "EstimatedTime"), new {@class = "ListBoxClass", @style = "height: 325px;"})
@Html.TextBoxFor(model => model.Name, new {@class = "TimeClass"})
<script type="text/javascript">
$(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
// get items properties and info so that the value can be set to a textbox
//set textbox value to Name of selected Value
$(".TimeClass").val(selectedid);
event.preventDefault(); // Stop the browser from redirecting as it normally would
$.get('@Url.Action("UserStoriesList", "Estimate")', { id: selectedid }, function (result) {
$('#stories').html(result);
});
});
});
</script>
Upvotes: 2
Views: 1519
Reputation: 1038890
A ListBox is like a DropDownList except that it allows for multiple items to be selected. It uses the same HTML tag (<select>
) but it adds the multiple
attribute. So when rendered your markup will look like this:
<select id="ListBoxName" name="ListBoxName" multiple="multiple">
<option value="id1">text 1</option>
<option value="id2">text 2</option>
<option value="id3">text 3</option>
...
</select>
So as you can see you have information about the id and the text inside the DOM. If you wanted to fetch some other information about the selected item you will need to send an AJAX request to the server and pass the selected id to retrieve it. So if you only wanted to show the text:
$(function() {
$('.ListBoxClass option').click(function() {
if ($(this).is(':selected')) {
var selectedId = $(this).val();
var selectedText = $(this).text();
$('.TimeClass').val(selectedText);
...
}
});
});
The click
handler will run everytime the user clicks on an element in the listbox but the if condition will be satisfied only if he selected the item.
Upvotes: 3