简体   繁体   中英

MVC - Change Label(s) on DropDown Selection - Strongly Typed View

MODEL - Employee.cs

public class Employee
{
    public int id { get; set; }
    public string name { get; set; }
    public int age { get; set; }

    public List<Employee> lstEmployees { get; set; }
}

CONTROLLER - EmpController.cs

public ActionResult Index()
    {
        Employee emp = new Employee();
        emp.lstEmployees = new List<Employee>();
        emp.lstEmployees.Add(new Employee() { id = 1, name = "ABCD", age = 15 });
        emp.lstEmployees.Add(new Employee() { id = 2, name = "EFGH", age = 25 });
        emp.lstEmployees.Add(new Employee() { id = 3, name = "IJKL", age = 35 });

        ViewBag.EmpList = emp.lstEmployees;

        return View();
    }

VIEW - Index.cshtml

@Html.DropDownListFor(m => m.id, new SelectList(ViewBag.EmpList, "id", "name"), new { onchange = "SelectedIndexChanged(this)" })


   <script type="text/javascript">
   function SelectedIndexChanged(p) {

   }
   </script>

I want to display age at label @Html.LabelFor(model => model.age) on change of selection of drop down.

Try this..

<script type="text/javascript">
  function SelectedIndexChanged(element) {
     var optionSelected = $("option:selected", element);
     var selectedAge = $(optionSelected).attr('data-age');
     $('label[for="age"]').text(selectedAge);
  }
</script>

It will add the label text with dropdown value.. Also you can try with this: $('label[for="age"]').html(selectedAge);

Edited:

<select name="id" id="id" onchange="SelectedIndexChanged(this)">
  @if(ViewBag.EmpList != null)
  {
      foreach(var item in ViewBag.EmpList){
          <option value="@item.id" data-age="@item.age">@item.name</option>
      }
  }
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM