我正在使用 ASP.NET MVC,并且正在尝试构建一个投票系统,类似于 stackoverflow。
我希望当我单击投票按钮时,在某个操作上发表帖子,在那里进行一些检查,但保留在我的初始页面上,如果检查通过,则增加投票(使用js)(就像所以)。
我想要投票的项目由索引操作填充
查看
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div><input type="submit" name="Vote" value="" class="fa fa-angle-up"/>
</div>
<div>@Html.DisplayFor(modelItem => item.Votes)</div>
<div><input type="submit" name="Vote" value="" class="fa fa-angle-down" /></div>
}
行动
public ActionResult SendVote(string vote)
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<VoteLogViewModel, VoteLog>());
var mapper = config.CreateMapper();
switch (vote)
{
case "":
if (ModelState.IsValid)
{
//Send to db
VoteLogViewModel voteLogViewModel = new VoteLogViewModel
{
DateAdded = DateTime.Now,
Id = Guid.NewGuid().ToString(),
PlaceId = id,
UserId = User.Identity.GetUserId(),
Vote = 1
};
db.VoteLogs.Add(mapper.Map<VoteLog>(voteLogViewModel));
db.SaveChanges();
}
else
{
return RedirectToAction("Index");
}
break;
case "":
if (ModelState.IsValid)
{
//Send to db
}
else
{
return RedirectToAction("Index");
}
break;
}
return new EmptyResult();
}
如何在不重新加载整个页面的情况下投票?
我应该在投票图标下创建一些链接并以某种方式通过路由来处理这个问题吗?
最佳答案
你需要做的是使用Ajax
示例:
查看
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div><input type="submit" name="Vote" value="true" class="fa fa-angle-up"/>
</div>
<div>@Html.DisplayFor(modelItem => item.Votes)</div>
<div><input type="submit" name="Vote" value="false" class="fa fa-angle-down" /></div>
}
<script>
$(function(){
$('input[name="Vote"]').click(function(e){
e.preventDefault();
var result = e.data.value;
$.ajax({
type: "POST",
url: url // ActionURL,
data: result,
success: function(data) { //Success here },
});
});
});
</script>
Controller
public ActionResult SendVote(bool vote)
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<VoteLogViewModel, VoteLog>());
var mapper = config.CreateMapper();
if(!ModelState.IsValid)
{
return RedirectToAction("Index");
}
if(vote)
{
//Send to db
VoteLogViewModel voteLogViewModel = new VoteLogViewModel
{
DateAdded = DateTime.Now,
Id = Guid.NewGuid().ToString(),
PlaceId = id,
UserId = User.Identity.GetUserId(),
Vote = 1
};
db.VoteLogs.Add(mapper.Map<VoteLog>(voteLogViewModel));
db.SaveChanges();
}
else
{
//Send to db
}
return new EmptyResult();
}
请注意,它在语法上可能不正确,因为我是在 IDE 外部编写的。但这应该能让你继续前进。
我还重构了您的 Controller 以使用 bool
而不是切换字符串。
关于javascript - 类似于 ASP.NET MVC 中的 SO 的投票系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38074891/