javascript - 如何在控制器中以 json 格式返回我的响应。(ASP.NET)
问题描述
我使用 toastr 来通知我的表单。我总是收到错误消息,但数据保存在数据库中。我认为错误来自控制器,因为我没有在 json 中发回。谢谢你的帮助。
-----控制器:---------------
public ActionResult CreateNewRentals(NewRentalDto newRental)
{
var hour = DateTime.Now;
var customer = _context.Customers.Single(
c => c.Id == newRental.CustomerId);
var movies = _context.Movie.Where(
c => newRental.MovieId.Contains(c.Id)).ToList();
foreach (var movie in movies)
{
if (movie.NumberAvailable == 0)
return BadRequest("le film est introuvable");
movie.NumberAvailable--;
var rental = new Rental
{
Customer = customer,
Movie = movie,
DateRented = DateTime.Now
};
_context.Rentals.Add(rental);
}
_context.SaveChanges();
return Ok();
}
----------------La view --------------------------------
<script type="text/javascript">
$(document).ready(function () {
var vm = {
movieId: []
};
var customers = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: customers,
remote: {
url: '/api/customers?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#customer').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
name: 'customers',
display: 'name',
source: customers
}).on("typeahead:select", function (e, customer) {
vm.customerId = customer.id;
});
/* MOVIES */
var movies = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/movies?query=%QUERY',
wildcard: '%QUERY'
}
});
$('#movie').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
name: 'movies',
display: 'name',
source: movies
}).on("typeahead:select", function (e, movie) {
$("#movies").append("<li class='list-group-item'>" + movie.name + "</li>");
$("#movie").typeahead("val", "");
vm.movieId.push(movie.id);
});
$("#newRental").submit(function (e) {
e.preventDefault();
$.ajax({
url: "/api/newRentals",
method: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(vm),
success: function (data) {
toastr.success(' successfully!');
},
error: function () {
toastr.error( 'error!');
}
});
});
});
</script>
解决方案
您没有将任何内容传递给 Ok() 结果。像这样传递一个值:返回 Ok(OBJECT HERE) 或返回新的 JsonResult(OBJECT HERE)。不同之处在于 Ok() 返回 HTTP 状态 200。
推荐阅读
- json - 如何根据键前缀解码 JSON 对象
- html - 如何更新 csv 文件以记录使用 toggleClass jQuery 函数实现的用户选择的图像?
- javascript - chrome.runtime.sendMessage 从后台脚本收到空响应
- multithreading - 为当前调用子程序下方的对象提供变量的正确方法?
- php - 试图做一个 div 循环
- android - 如何在 6 月/7 月安全更新后为 Android 主屏幕小部件实现自定义字体?
- r - 如何将字符向量列表转换为 quanteda 令牌对象?
- angular - Angular - ng-pick-datetime:如何以反应形式初始化输入值
- python - 如何交换 s 字符串的 2 部分?
- wordpress - 我需要 gitignore 忽略除一个文件夹及其中的所有内容之外的所有内容