步骤 1) 修改视图以使计数器可被 jquery 寻址:
@model Contoso.MvcApplication.ViewModels.QuizCompletedViewModel
<p id="my-counter">@Model.Property1</p>
现在,您需要服务器上的这个递增值吗?
如果您不需要将此递增值发送到服务器:
第 2 步)使用 javascript/jquery 增加客户端上的值:
$("#my-image").click(function () {
var theValue = parseInt($("#my-counter").html());
theValue = theValue + 10;
$("#my-counter").html(theValue);
});
如果您确实需要在服务器上增加:
步骤 2) 创建一个控制器动作来处理增量
public ActionResult Increment(int currentValue)
{
// save to the database, or do whatever
int newValue = currentValue + 10;
DatabaseAccessLayer.Save(newValue);
Contoso.MvcApplication.ViewModels.QuizCompletedViewModel model = new Contoso.MvcApplication.ViewModels.QuizCompletedViewModel();
model.Property1 = newValue;
// If no exception, return the new value
return PartialView(model);
}
第 3 步)创建一个仅返回新值的局部视图
@model Contoso.MvcApplication.ViewModels.QuizCompletedViewModel
@Model.Property1
步骤 4) 修改 jquery 以发布到这个新动作,它返回新的计数,并显示它
$("#my-image").click(function () {
$.get('/MyController/Increment/' + $("#my-counter").html(), function(data) {
$("#my-counter").html(data);
});
});
代码未经测试,但我认为非常接近,希望这能给出正确的想法。