开发者

Binding Dropdown selected value to Label in MVC2

开发者 https://www.devze.com 2023-01-25 05:41 出处:网络
I am new to VS 2010 and MVC2.Here i had populated a dropdownlist from database. My HomeControler Source Code will be

I am new to VS 2010 and MVC2.Here i had populated a dropdownlist from database. My HomeControler Source Code will be ` namespace SampleControls.Controllers {

public class HomeController : Controller
{
    SControlsDataContext data = new SControlsDataContext();

    public ActionResult Index()
     {
         var Emp = from prod in data.Emps
                   select prod;
         ViewData["Emps"] = Emp;
         return View();
     }      

    public ActionResult About()
    {
        return View();
    }

}

} `

and my Index.aspx will be

<% using (Html.BeginForm()) { %> <%= Html.DropDownList("lstProducts", new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), new { onChange = "onSelectedIndexChanged()" })%> <% } %>

what i want is " on the SelectedIndexChanged, the selected value should be displayed in a label.

 <script type="text/javascript">
    function onSelectedIndexChanged() 
      {
       //i know i should write the code here for binding the dropdown selected value to label... But, i dont know how to do this.
      }
</script> 
开发者_运维技巧


<% using (Html.BeginForm()) { %> 
    <%= Html.DropDownList("lstProducts", 
        new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), 
        new { onchange = "onSelectedIndexChanged(this.value)" })%> 
<% } %>

<div id="foo"></div>

and then:

function onSelectedIndexChanged(value) {
    document.getElementById('foo').innerHTML = value;
}

UPDATE:

In order to get the selected text:

<% using (Html.BeginForm()) { %> 
    <%= Html.DropDownList("lstProducts", 
        new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), 
        new { onchange = "onSelectedIndexChanged(this)" })%> 
<% } %>

function onSelectedIndexChanged(select) {
    var text = select.options[select.selectedIndex].text;
    document.getElementById('foo').innerHTML = text;
}

UPDATE 2:

The same could be achieved with jquery:

<% using (Html.BeginForm()) { %> 
    <%= Html.DropDownList("lstProducts", 
        new SelectList((IEnumerable)ViewData["Emps"], "Id", "Name"), 
        new { id="myselect" })%> 
<% } %>

and then:

$(function() {
    $('#myselect').change(function() {
        var text = $(this).find('option:selected').text();
        $('#foo').html(text);
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号