CSharp · Mvc
using System;
using System.ComponentModel.DataAnnotations;
namespace Sample
{
public class Cliente
{
public int Id { get; set; }
public string Nome { get; set; }
public int IdGrupoCliente { get; set; }
}
public class ModelForm
{
public int IdCliente { get; set; }
}
}
@model Sample.ModelForm
@{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<select class="form-control" name="@Html.NameFor(model => model.IdCliente)" id="@Html.IdFor(model => model.IdCliente)">
<option></option>
@foreach(var cliente in ViewData["Clientes"] as List<Sample.Cliente>)
{
<option data-id-grupo-cliente="@cliente.IdGrupoCliente" value="@cliente.Id">@cliente.Nome
</option>
}
<select>
<div id="grupo-sel">
</div>
</div>
</body>
<script>
var select = document.querySelector('#@Html.IdFor(model => model.IdCliente)');
select.addEventListener('change', function() {
var option = this.options[this.selectedIndex];
document.querySelector('#grupo-sel').innerHTML = option.getAttribute('data-id-grupo-cliente');
});
</script>
</html>
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace Sample
{
public class HomeController : Controller
{
private List<Cliente> _clientes = new List<Cliente>
{
new Cliente { Id = 1, Nome = "Julius", IdGrupoCliente = 2 },
new Cliente { Id = 2, Nome = "Chris", IdGrupoCliente = 1 },
new Cliente { Id = 3, Nome = "Drew", IdGrupoCliente = 2 },
new Cliente { Id = 4, Nome = "Tonya", IdGrupoCliente = 1 },
new Cliente { Id = 5, Nome = "Rochelle", IdGrupoCliente = 2 }
};
[HttpGet]
public ActionResult Index()
{
ViewData["Clientes"] = _clientes;
return View();
}
}
}