我想使用按钮点击从数据库中逐个显示记录。这是我在控制器中的动作方法
public ActionResult ApplyJobs(int? id, int x)
{
TblConsultancies consultancyJobs = _obj.TblConsultancies.ToList().Skip(x).FirstOrDefault();
return View(consultancyJobs);
}
JQuery AJAX代码:
<script>
var numberofRecords;
$(document).ready(function () {
numberofRecords = 1;
},
function FetchRecord(){
$.ajax({
type: "GET",
url: "/Home/ApplyJobs",
data: {
recNo: numberofRecords
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
numberofRecords+=1;
alert("success...");
var cars = response.d;
$('#output').empty();
$.each(cars, function (index, car) {
$('#output').append('<tr><td>' + car.Name + '</td></tr>');
});
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
);
</script>
HTML:
<div id="output">@Model.Name</div>
当我手动输入/Home/ApplyJobs?x=1
时,从上面的代码中。
它正在运作。但我只想在单击“下一步”按钮时显示。
我怎样才能逐一记录?感谢。
答案 0 :(得分:0)
而不是注册Next按钮的onclick事件,而不是onclick对象的属性。
<input id="btnNext" type="button" title="Next" value="Next" onclick="FetchRecord()" />
var numberofRecords;
$(document).ready(function () {
numberofRecords = 1;
}
function FetchRecord(){
$.ajax({
type: "GET",
url: "/Home/ApplyJobs",
data: {
recNo: numberofRecords
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
numberofRecords+=1;
alert("success...");
var cars = response.d;
$('#output').empty();
.each(cars, function (index, car) {
$('#output').append('<tr><td>' + car.Name + '</td></tr>');
});
},
failure: function (msg) {
$('#output').text(msg);
}
});
});
}
而不是返回ActionResult而是尝试返回JsonResult
public JsonResult ApplyJobs(int recNo)
{
TblConsultancies consultancyJobs = _obj.TblConsultancies.ToList().Skip(recNo).FirstOrDefault();
return Json(consultancyJobs);
}
答案 1 :(得分:0)
首先是动作方法。您希望返回其Name
属性排序的TblConsultancies
下一个ID
属性。因此,您需要传入当前ID
并返回下一个ID
和Name
[HttpGet]
public JsonResult ApplyJobs(int id)
{
// Get the next TblConsultancy
var next = _obj.TblConsultancies.OrderBy(j => j.ID).Where(j => j.ID > id).FirstOrDefault();
if(next == null)
{
return null;
}
else
{
// Select the ID and Name
var data = new
{
ID = next.ID,
Name = next.Name
};
return Json(data, JsonRequestBehavior.AllowGet);
}
}
查看(不要混淆标记和行为 - 使用Unobtrusive Javascript)
<div id="output">@Model.Name</div>
<button id="next" type="button" title="Next">Next</button>
脚本
var ID = '@Model.ID'; // or var ID = 1; if your not initially rendering an object
var url = '@Url.Action("ApplyJobs", "Home")'; // don't hard code url's!
var output = $('#output'); // cache it
$('#next').click(function() {
$.getJSON(url, { id: ID }, function(data) {
if(data) {
ID = data.ID; // reset the current ID
output.html(data.Name); // display the name
} else {
// no more objects - display message, disable the button?
}
});
});