后台代码:
public class DropController : Controller
{
// GET: Drop
public ActionResult Index()
{
List<Province> list = new List<Province>
{
new Province{ Id=1,name="山西省"},
new Province{ Id=1,name="广东省"},
new Province{ Id=1,name="山东省"},
new Province{ Id=1,name="河北省"},
new Province{ Id=1,name="湖南省"}
};
var dropDownList = new SelectList(list, "Id", "name");
ViewBag.dropDownList = dropDownList;
return View();
}
}
public class Province
{
public int Id { get; set; }
public string name { get; set; }
}
前台代码:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/layui/css/layui.css" rel="stylesheet" />
<script src="~/layui/layui.js"></script>
<script src="~/Scripts/jquery-3.3.1.js"></script>
<style>
.layui-form-select dl dd.layui-this {
background-color: #1E9FFF;
}
</style>
</head>
<body>
<div>
主页
</div>
<div class="layui-form">
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">选择省份:</label>
<div class="layui-input-inline">
@Html.DropDownList("province", ViewBag.dropDownList as SelectList, "请选择省份", new { @class = "form-control input-small" })
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">选择市区:</label>
<div class="layui-input-inline">
<select name="quiz2">
<option value="">请选择市</option>
<option value="杭州">杭州</option>
<option value="宁波">宁波</option>
<option value="温州">温州</option>
<option value="温州">台州</option>
<option value="温州">绍兴</option>
</select>
</div>
</div>
</div>
</div>
<script>
layui.use([‘layer‘, ‘form‘], function () {
var layer = layui.layer
, form = layui.form;
form.render();
});
</script>
</body>
</html>
这里在后台代码中
var dropDownList = new SelectList(list, "Id", "name");
ViewBag.dropDownList = dropDownList;
表示新建了一个SelectList 其中Id用作下拉框绑定的value name表示下拉框绑定的text 然后将数据保存在viewbag中
@Html.DropDownList("province", ViewBag.dropDownList as SelectList, "请选择省份", new { @class = "form-control input-small" })
这一段前台的razor代码 其中"province"表示下拉框的id和name ,前台选择用的那个 ViewBag.dropDownList as SelectList表示要绑定到下拉框的数据 "请选择省份"是要绑定下拉框的提示项
new { @class = "form-control input-small" } 表示前台那个类属性.
接下来加一个按钮 看能不能获取到点击的值
可以获取 代码如下:
layui.use([‘layer‘, ‘form‘], function () {
var layer = layui.layer
, form = layui.form;
form.render();
$("#btnTest").click(function () {
var value = $("#province").val();
layer.alert("选中的值是" + value);
});
});
这里这个说明 在使用razor语法来做数据绑定 前台也可以使用layui的样式
原文地址:https://www.cnblogs.com/yagamilight/p/12321951.html