我是asp.net MVC的新手,我正在做一个项目,就像堆栈溢出一样。在此,我只想使用ajax系统来投票或否决答案。因此,我可以显示计数器的增加和减少而无需刷新页面。
我在Question
中有一个默认的controller
控制器脚手架,其中有一个QuitionDetails
负责QuitionDetailsView
的方法,在这种情况下,我向ajax请求我的API
控制器VotesController
当用户单击上投票或下投票时。
但是我遇到了这个错误
jquery-3.3.1.js:9600 PUT https://localhost:44389/Question/QuestionDetails/api/votes/3 404 not found
send @ jquery-3.3.1.js:9600
ajax @ jquery-3.3.1.js:9206
(anonymous) @ 2:230
dispatch @ jquery-3.3.1.js:5183
elemData.handle @ jquery-3.3.1.js:4991
这是我的第一个默认脚手架控制器Question
public ActionResult QuestionDetails(int Id)
{
QuestionDetailViewModel questionDetailViewModel = new QuestionDetailViewModel
{
Question = QBL.GetQuestions(Id),
UserId = User.Identity.GetUserId(),
QuestionId = Id,
};
return View(questionDetailViewModel);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult QuestionDetails(QuestionDetailViewModel questionDetailViewModel)
{
QBL.CreateAnswer(questionDetailViewModel);
return RedirectToAction("QuestionDetails", new { Id = questionDetailViewModel.QuestionId });
}
查看代码如下
@model AskMe.Models.ViewModel.QuestionDetailViewModel
@{
ViewBag.Title = "QuestionDetails";
}
<h1>Question Details: </h1>
<h3>@Model.Question.Post.Title</h3>
@Html.Raw(Model.Question.Post.Content)
<hr />
<h3>Answers:</h3>
@foreach (var answer in Model.Question.Answers)
{
<div class="card bg-light m-1">
<div class="card-body">
<h5 class="card-title">Answered by: @answer.Post.CreatedBy.UserName</h5>
@Html.Raw(answer.Post.Content)
</div>
<div id="vote" class="col">
<div>
<button data-vote-id="@answer.Post.PostId" class="nav-link thumbs-up" href=""><i class="fa fa-thumbs-up" aria-hidden="true"></i></button>
</div>
<div>
</div>
<div>
<button data-vote-id="@answer.Post.PostId" class="nav-link thumbs-down" href=""><i class="fa fa-thumbs-down" aria-hidden="true"></i></button>
</div>
</div>
</div>
}
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h3>Contribute your answer: </h3>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(m => m.AnswerContent, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextAreaFor(m => m.AnswerContent, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
@Html.HiddenFor(m => m.UserId)
@Html.HiddenFor(m => m.QuestionId)
<input type="submit" value="Contribute now" class="btn btn-outline-primary" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval");
<script type="text/javascript">
$(document).ready(function () {
tinyMCE.init({
mode: "textareas",
});
$("#vote").on("click",".thumbs-up", function () {
console.log("in selection func");
$.ajax({
url: "api/vote/" + $(this).attr("data-vote-id"),
method: "PUT",
success: function () {
console.log("success");
}
})
})
});
</script>
}
这是我的votes
API
控制器代码
using AskMe.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace AskMe.API
{
public class VotesController : ApiController
{
ApplicationDbContext _context = new ApplicationDbContext();
[HttpPut]
public IHttpActionResult UpVote(int postId)
{
var userId = User.Identity.GetUserId();
var user = _context.Users.Find(userId);
var post = _context.Posts.Find(postId);
var votes = post.Votes.ToList();
if (votes.FindAll(u => u.UserId == userId).Count == 0)
{
Votes vote = new Votes
{
VotedDateTime = DateTime.Now,
UserId = userId,
User = user,
Post = post,
PostId = postId,
};
post.Votes.Add(vote);
_context.SaveChanges();
return Ok();
}
return BadRequest();
}
}
}
我不确定我的api链接应该是这样的https://localhost:44389/Question/QuestionDetails/api/votes/3
要么
https://localhost:44389/api/votes/3
而我的路由配置为routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
答案 0 :(得分:1)
如果您尚未更改标准路由,则需要在ajax调用中包括操作/方法名称。
尝试:
url: "api/vote/upvote/" + $(this).attr("data-vote-id")
您的路由配置应如下所示:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
如果您将MVC5与WebApi一起使用,这是我的猜测,则必须小心。有关如何操作的更多信息,请参见this。
答案 1 :(得分:0)
实际上,您的错误告诉了一切。当您请求“ UpVote”操作时,它正在查找“ basepath(localhost)/ controller / action / Api / etc”。它不会退出。您必须为https://localhost:44389/API/Votes/UpVote/3
答案 2 :(得分:-1)
如果要从ajax调用控制器操作,则必须在ajax调用的url部分中提及控制器名称和操作方法。