Reputation: 747
I want to display the price of the selected item in the textbox in the view. For example, a product selected from the DLL has a price of 10 € and it should be displayed in the view. Can someone help?
Controler
public ActionResult Edit(int id)
{
Product product = DB.Products.Find(id);
ViewBag.Formats = new SelectList(storeDB.Format, "FormatID", "FormatName", "Price");
ViewBag.Foo = "Some Value"; //test
return View(product);
}
View
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-field">
@Html.DropDownList("Formats", ViewBag.Formats as SelectList, new { id = "DDLFormatsID" })
@Html.Display("Price") //displays nothing
@Html.Display("Foo") //working properly
</div>
</fieldset>
}
Update:
Upvotes: 0
Views: 1363
Reputation: 2427
The problem seems to be in the order of the parameters in the constructor of the SelectList
. I changed this line and it worked as you expected, showing the prices.
ViewBag.Formats = new SelectList(storeDB.Format, "FormatID", "Price");
You can check for the use of each parameter in the constructor. The first is for the data, the second is the name of the property that will hold the data to be send on the post, the third is the name of the property to be displayed.
Answer to the updated question:
If you want to show some value depending on the value in the dropdown then you can do it using javascript. First You have to identify the control to put your value, I'll use a span but you can use a textbox, etc. Then you subscribe to the change event of the dropdown and change the content of the first control every time.
Note that I'm using the value of the select to store the prices. If you want to receive the value as the id of the item you cannot use this approach. You need to store the prices in another place, you can use hidden elements.
You have to reference the jQuery library in the view.
The code is this:
public ActionResult Edit(int id)
{
Product product = DB.Products.Find(id);
ViewBag.Formats = new SelectList(storeDB.Format, "Price", "FormatName");
return View(product);
}
View
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-field">
@Html.DropDownList("Formats", ViewBag.Formats as SelectList, new { id = "DDLFormatsID" })
<span id="priceHolder"></span>
</div>
</fieldset>
}
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#Formats").change(function () {
var $this = $(this);
var selectedValue = $this.val();
$('#priceHolder').html(selectedValue);
});
});
</script>
Upvotes: 1