【发布时间】:2014-08-06 16:48:49
【问题描述】:
我试图在双击时按单元格而不是按行进行内联编辑。这很有效,但它不会更新记录 - 没有对控制器进行“SaveCustomer”调用。我做错了什么?
这是我的索引视图文件(部分,其余无关)
@foreach (var item in Model.Drivers)
{
<tr id="@item.ID">
<td id="id">
@Html.DisplayFor(modelItem => item.ID)
</td>
<td id="lastName">
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td id="firstName">
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td id="seniority">
@if (item.Seniority != null) {@Convert.ToDateTime(item.Seniority).ToShortDateString()}
</td>
<td>
<td> //more go here </td>
然后这里是 javascript 文件 - 抱歉格式化,每次我复制和粘贴时都会发生
$("td").dblclick(function () {
if (!$(this).hasClass("edit")) {
var value = jQuery.trim($(this).html());
$(this).html("<input id=\"txtEdit\" type=\"text\" class=\"textbox\" value=\"" + value + "\" onblur=\"SaveValue(this, '" + value + "')\" onfocus=\"PutCursorAtEnd(this)\" />");
$(this).addClass("edit");
$("#txtEdit").focus();
}
});
function PutCursorAtEnd(obj) {
if (obj.value == obj.defaultValue) {
$(obj).putCursorAtEnd(obj.length);
}
}
function SaveValue(obj, oldValue) {
var value = $(obj).val();
$(obj).parent().removeClass("edit");
if (value != oldValue) {
var property = $(obj).parent().attr("id");
var id = $(obj).parent().parent().attr("id");
$.ajax({
type: "POST",
url: '@Url.Action("SaveCustomer", "save")',
data: { ID: id, Property: property, Value: value },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: SaveCustomer_Success,
error: Error
});
}
else {
$(obj).parent().html(oldValue);
}
}
function SaveCustomer_Success(data, status) {
$(data.d.ID).parent().html(data.d.NewValue);
}
最后是控制器方法
public object SaveCustomer(int ID, string Property, string Value)
{
Driver driver = unitOfWork.DriverRepository.GetByID(ID);
switch(Property) {
case "id":
driver.ID = Convert.ToInt32(Value);
break;
case "firstName":
driver.FirstName = Value;
break;
case "lastName":
driver.LastName = Value;
break;
case "seniority":
driver.Seniority = Convert.ToDateTime(Value);
break;
}
unitOfWork.DriverRepository.Update(driver);
unitOfWork.Save();
return new
{
ID = ID,
NewValue = Value
};
}
非常感谢您的帮助,谢谢!
【问题讨论】:
-
您是否在 SaveCustomer() 中设置了断点?它会被击中吗? SaveCustomer 控制器方法不应该返回 ActionResult 吗?路线是什么样的?
-
SaveValue js函数在哪里调用?
-
这是非常脆弱的代码。我可以很容易地看到多个故障点,这是维护的噩梦。老实说,我建议您重新开始,最好是在一些教程或文章的指导下,您应该能够在简单的 Google 搜索中找到(这是一个相当常见的场景)。即使您解决了这个迫在眉睫的问题,您还是会回来寻找无数轮额外的 SO 问题以使此功能正常运行。
-
@JamesLawruk 我确实在函数中放了一个断点,但它没有被命中。
-
和 @BobMac 它在第一个函数中调用 $(this).html("");
标签: javascript jquery ajax asp.net-mvc inline-editing