我是JavaScript的新手,之前从未使用过Ajax。我想在Index.cshtml中添加一个OnClick,所以当单击一行时,我的代码将查询数据库(MSSQL)并返回结果。 我在数据库中有两个表,User和Contact。 User中的主键UID是Contact中的外键。这是我的代码:
控制器
private UserInfoEntities db = new UserInfoEntities();
public ActionResult Index(){
var users = from u in db.User orderby u.UID select u;
return View(users.ToList());
}
查看
@<Info.Model.User>
<script type="text/javascript">
function showEmail() {
var tb = document.getElementById("users");
var rows = tb.rows;
for (var i = 1; i < rows.length; i++) {
rows[i].onclick = (function() {
//some code that query Contact table using UID
// and return Contact.Email in a popup windows or something
});
}
}
</script>
<table class="table" id="users" onclick="showEmail()">
<tr>
<th>
@Html.DisplayNameFor(model => model.NAME)
</th>
<th>
@Html.DisplayNameFor(model => model.UID)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
@Html.DisplayFor(modelItem => item.UID)
</td>
</tr>
感谢任何帮助!
答案 0 :(得分:1)
试试这个;
<script type="text/javascript">
function showEmail() {
//some code that query Contact table using UID
// and return Contact.Email in a popup windows or something
}
</script>
<table class="table" id="users" >
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().NAME)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().UID)
</th>
</tr>
@foreach (var item in Model) {
<tr onclick="showEmail()">
<td>
@Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
@Html.DisplayFor(modelItem => item.UID)
</td>
</tr>
}