我正在将这个小功能添加到 MVC 网站上最喜欢的项目中,并且在 UI 端开发它时遇到了一些困难。我已经更改了更改的处理和数据库方面。
它按原样工作,但我需要刷新页面才能看到按钮更改为“添加收藏夹”到“删除收藏夹”类型的图标。
我的视图中的丑陋代码在这里。
@{
if(ViewBag.IsFavourited == true)
{
<script type="text/javascript">
$(function () {
$("#addfavourite").hide();
});
</script>
}
else
{
<script type="text/javascript">
$(function () {
$("#deletefavourite").hide();
});
</script>
}
}
<div id="deletefavourite" class="pull-right">
@Ajax.ActionLink("Unfavourite", "Delete", "Favourite", new { id = Model.BlogPostId },
new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "deletefavourite", LoadingElementId = "addfavourite" }, new { @class = "deletefavourite" })
</div>
<div id="addfavourite" class="pull-right">
@Ajax.ActionLink("Add to favourites", "Add", "Favourite", new { id = Model.BlogPostId },
new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "addfavourite", LoadingElementId = "deletefavourite" }, new { @class = "addfavourite" })
</div>
如果您可能还需要查看来自 Controller 的代码
public ActionResult Details(int id)
{
BlogPostViewModel blogpost = waclient.GetBlogPostById(id);
Favourite favourite = blogpost.Favourites.SingleOrDefault(u => u.BlogPostBlogPostId == blogpost.BlogPostId && u.UserId == User.Identity.Name);
if (favourite != null)
{
ViewBag.IsFavourited = true;
}
else
{
ViewBag.IsFavourited = false;
}
if (blogpost == null)
{
return HttpNotFound();
}
return View(blogpost);
}
CSS 使链接成为图标
<style type="text/css">
.addfavourite {
background-image: url('@Url.Content("~/Content/Images/heart-black.png")');
background-repeat: no-repeat;
display: block;
text-indent: -9999px;
height: 50px;
width: 50px;
}
.deletefavourite {
background-image: url('@Url.Content("~/Content/Images/heart-checked.png")');
background-repeat: no-repeat;
display: block;
text-indent: -9999px;
height: 50px;
width: 50px;
}