I am using asp.net mvc2.I have a listbox and textbox when i select an item from listbox corresponding value to that item should appear in textbox from database.please help
-
what did you try so far? how do you load the data from the database? Share some code please!Davide Piras– Davide Piras2011-08-23 11:51:07 +00:00Commented Aug 23, 2011 at 11:51
-
i don't have any code.my requirement is like this eg: i have machine name in listbox when i select one item price of that machine come in textbox..how its is done in mvc2 asp.netjoms– joms2011-08-23 13:03:00 +00:00Commented Aug 23, 2011 at 13:03
2 Answers
You should use JavaScript for handle listbox selection changes.
And read about Ajax, it neads to get the data from DB without reloadin page.
Add
Example how can you handle listbox selection changes.
@Html.ListBox("nam",new SelectList(new string[]{"opt1","opt2"}),new {onchange = "javaScript:actch()", id = "namid"})
<script type="text/javascript">
function actch() {
alert(document.getElementById("namid").value);
}
</script>
Value "document.getElementById("namid").value" contains option that you select.
You should send this value to the server and recieve request
@Html.ListBox("nam",new SelectList(new string[]{"opt1","opt2"}),new {onchange = "javaScript:actch()", id = "namid"})
<script type="text/javascript">
function actch() {
$.ajax({
url: "your url",
type: "POST",
data: "id = " + document.getElementById("namid").value,
success: function (data) {
// action on success
document.getElementById("TextBoxId").value = data;
},
error: function (jqXhr, textStatus, errorThrown) {
// action on fail
},
complete: function () {
}
});
}
</script>
You have to write a server request part, and configure ajax. (I had use jQuery)
Added: Server request part (example)
[HttpPost]
public MvcHtmlString Detail(string id)
{
var d = _db.GetVehicle(Convert.ToInt32(id));
var sb = new StringBuilder();
sb.AppendLine(string.Format("Type: {0}</br>", d.Type));
sb.AppendLine(string.Format("Brand: {0}</br>", d.Brand));
sb.AppendLine(string.Format("Model: {0}</br>", d.Model));
sb.AppendLine(string.Format("Number: {0}</br>", d.Number));
sb.AppendLine(string.Format("Year: {0}</br>", d.Year));
sb.AppendLine(string.Format("Cost: {0}</br>", d.Cost));
return new MvcHtmlString(sb.ToString());
}
URL looks like: MyController/Detail/
DATA for ajax: "id=" + document.getElementById("namid").value
P.S. Some one edit/spoil my ansver and it's not marked(
3 Comments
Your question is a little vague but this is basically how it can be done:
You can post the value of the listbox in the change event by using jquery (or any other JS library of your preference). Then the controller gives a value back, which you then put in the textbox.
Check out http://api.jquery.com/jQuery.post/