我正在通过 本教程. 我来到了为复选框添加事件处理程序的部分。 我在这方面遇到了一些麻烦,所以我放入了 alert() 调用,这样我就可以看到脚本正在执行。 我还在控制器中调用Console.WriteLine()来报告何时成功处理了一个框,何时失败。
当我在markCompleted()函数中的alert()调用时,消息出现了两次。 而在运行项目的控制台窗口中,我首先看到的是成功的报告,然后是失败的报告。 看来,当出现alert()调用时,复选框的点击事件被激发了两次。 为什么会出现这种情况? 当我删除alert()调用时,我在控制台窗口中只得到一条消息,操作成功。
这是教程中告诉我放入的JavaScript。
$(document).ready(function () {
// Wire up all of the checkboxes to run markComnpleted()
//alert("Document ready function");
$('.done-checkbox').on('click', function (e) {
markCompleted(e.target);
});
});
function markCompleted(checkbox) {
alert("Mark completed function.");
checkbox.disabled = true;
var row = checkbox.closest('tr');
$(row).addClass('done');
var form = checkbox.closest('form');
form.submit();
}
这是我的控制器代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AspNetCoreTodo.Services;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Controllers
{
public class ToDoController : Controller
{
private readonly IToDoItemService _toDoItemService;
public ToDoController(IToDoItemService toDoItemService)
{
_toDoItemService = toDoItemService;
}
public async Task<IActionResult> Index()
{
// Get to-do items from database
var items = await _toDoItemService.GetIncompleteItemsAsync();
// Put items into a model
var model = new ToDoViewModel()
{
Items = items
};
// Render view using the model
return View(model);
}
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddItem(ToDoItem newItem)
{
if (!ModelState.IsValid)
{
return RedirectToAction("Index");
}
var successful = await _toDoItemService.AddItemAsync(newItem);
if (!successful)
{
return BadRequest("Could not add item.");
}
return RedirectToAction("Index");
}
[ValidateAntiForgeryToken]
public async Task<IActionResult> MarkDone(Guid id)
{
if (id == Guid.Empty)
{
Console.WriteLine("Received invalid or empty Guid");
return RedirectToAction("Index");
}
bool successful = await _toDoItemService.MarkDoneAsync(id);
if (!successful)
{
Console.WriteLine("Failed to mark item as done.");
return BadRequest("Could not mark item as done.");
}
Console.WriteLine("Item marked done.");
return RedirectToAction("Index");
}
}
}
最后,这是服务的代码。
public async Task<bool> MarkDoneAsync(Guid id)
{
var item = await _context.Items
.Where(x => x.Id == id)
.SingleOrDefaultAsync();
if (item == null)
return false;
item.IsDone = true;
int saveResult = await _context.SaveChangesAsync();
return saveResult == 1;
}
可能有这两个问题中的一个:1.你同时包含了min.js和js,因此它绑定了两次事件。为了排除这个问题,在添加之前使用点击的解绑,在这种情况下,它应该发生一次.2.如果这没有帮助,你的事件可能会传播到父元素,你想在markcompleted被调用之前尝试e.PreventDefault()来排除这个问题。