我的代码存在问题,我尝试使用EF Code First从数据库更新一个字段。我在其他项目中使用相同的代码,因为我记得它工作正常,但我不知道为什么它现在不能正常工作。
以下是我的观点:
<p id="myElem" class="alert-danger" style="display:none"></p>
<button class="downcount btn btn-warning mt-15 btn-block" id="downcount" data-id="@Model.Post.Id"><i class="fa fa-cloud-download">Click Here</i></button>
<script type="text/javascript">
$('.downcount').click(function () {
var myId = $(this).data('id');
$.ajax({
type: "GET",
url: '@Url.Action("DownloadNum", "Course")?Post_id=' + myId,
success: function (response) {
$('#myElem').html(response).fadeIn('slow');
$('#myElem').delay(8000).fadeOut('slow');
},
failure: function (response) {
alert("Failure");
}
});
});
</script>
这是我的控制器:
[HttpGet]
public ActionResult DownloadNum(int Post_id)
{
var result = db.Post.Where(p => p.Id == Post_id).FirstOrDefault();
if (result != null)
{
result.DownloadCount = result.DownloadCount+1;
db.SaveChanges();
return Content("Download Started !");
}
else
{
return Content("File is not on the server or deleted, Please report us to renew it!");
}
}
我尝试调试和跟踪进程,没有问题或错误,只是在数据库保存并检查数据库没有更新或更改后!
答案 0 :(得分:0)
这是因为您没有添加,删除或修改数据库中的任何内容。我假设您要修改/编辑,因为您正在通过以下代码行搜索记录:
var result = db.Post.Where(p => p.Id == Post_id).FirstOrDefault();
// Id is a UNIQUE property, so technically you should be using .Single()
// or .SingleOrDefault() because there should only be ONE record where p.Id == Post_id
// or you could use:
// var result = db.Post.Find(Post_id);
然后,您想要修改该结果。
result.DownloadCount = result.DownloadCount+1;
db.Entry(result).EntityState = EntityState.Modified; // missing line
db.SaveChanges();
作为旁注,在你的jQuery中...如果你的视图使用模型..你可以改变这一行:
url: '@Url.Action("DownloadNum", "Course")?Post_id=' + myId,
要:
url: '@Url.Action("DownloadNum", "Course", new { Post_id = Model.Id })',
@Url.Action
已超载,您可以合并路线值。
请告诉我这是否有帮助!