gpt4 book ai didi

javascript - MVC - 更改下拉选择上的标签 - 强类型 View

转载 作者:行者123 更新时间:2023-12-03 03:54:01 24 4
gpt4 key购买 nike

模型 - 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)关于下拉选择的更改。

最佳答案

试试这个..

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

关于javascript - MVC - 更改下拉选择上的标签 - 强类型 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45033347/

24 4 0