MVC - 在DropDown选择上更改标签 - 强类型视图

时间:2017-07-11 11:31:18

标签: javascript jquery asp.net-mvc asp.net-mvc-4 razor

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();
    }

查看 - 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>

我想在标签上显示年龄 @Html.LabelFor(model => model.age) 关于下降选择的变化。

1 个答案:

答案 0 :(得分:1)

试试这个..

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

它将添加带有下拉值的标签文本。 您也可以试试这个:$('label[for="age"]').html(selectedAge);

编辑:

<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>