gpt4 book ai didi

c# - 在 Ajax-Jquery 成功时,如何在 ASP.NET MVC5 C# 中提交模态表单后替换或附加表的单元格值

转载 作者:行者123 更新时间:2023-11-30 22:58:49 25 4
gpt4 key购买 nike

当提交模态表单并成功关闭时,数据会更新到我的数据库表中,但我需要的是在没有页面刷新的情况下,数据应该在表的单元格中更新。

我是 JQuery 的新手,如果有人能帮我解决这个问题,我将不胜感激。

这是我放在部分 View 末尾的脚本:

function btndbsave(obj) {
var ele = $(obj);
var id = ele.attr("data-model-id");
var itemlist = [];
var name = $("[name = 'NameTxtID']").val();
var phone = $("[name = 'PhoneTxtID']").val();
var email = $("[name ='EmailTxtID']").val();
var AjaxVM = { Id: id, Name: name, Phone: phone, Email: email };
itemlist.push(AjaxVM);


console.log(itemlist)
debugger;
$.ajax({
url: '/Home/Edit', //
dataType: "json",
data: JSON.stringify({ AjaxVM }),
type: "POST",
contentType: "application/json; charset=utf-8",
success: function () {
alert("success");
$('#newmodal').modal('hide');
$('#tbDetails>tbody>td').find("tr").html(AjaxVM);

//$('#tbDetails').find("tbody>tr").append(itemlist);
},
error: function (xhr) {
alert("error");
}
});
};

部分 View 作为模态:

<div class="modal-header">
<h5 class="modal-title">Edit Record</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>

<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(x => x.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(x => x.Name, "NameTxt", "NameTxtID", new { htmlAttributes = new { @class = "form-control col-md-6", @name = "Name[]" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(x => x.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(x => x.Phone, "PhoneTxt", "PhoneTxtID", new { htmlAttributes = new { @class = "form-control col-md-6", @name = "Phone[]" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(x => x.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(x => x.Email, "EmailTxt", "EmailTxtID", new { htmlAttributes = new { @class = "form-control col-md-6", @name = "Email[]" } })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-primary btnSave" data-model-id="@Model.Id" onclick="btndbsave(this)" value="Save changes">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>

这是View的表格:

 <table id="tbDetails" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
<td>Phone</td>
<td>Email</td>
<td>Options</td>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td width="100" class="idField">@item.Id</td>
<td>@item.Name</td>
<td>@item.Phone</td>
<td>@item.Email</td>
<td>
<a class="delete" data-model-id="@item.Id" onclick="Delete(this)"><img src="/UserImages/delete.png" /></a>
<a class="edit-record" data-model-id="@item.Id" onclick="Edit(this)" ><img src="/UserImages/pencil.png" /></a>
</td>
</tr>
}
</tbody>
</table>

这是 Controller :

[HttpPost] 
public ActionResult Edit(Models.AjaxVM ajaxVM)
{
using (var db = new PracticeEntities())
{
var checkforid = db.AjaxTable.Where(x => x.Id == ajaxVM.Id).FirstOrDefault();
if (checkforid != null)
{
checkforid.Name = ajaxVM.Name;
checkforid.Email = ajaxVM.Email;
checkforid.Phone = ajaxVM.Phone;
db.SaveChanges();
}
else
{
ModelState.AddModelError("error", "Record has not been Updated");
}

return Json(ajaxVM);
}

}

在单独的 JS 文件中编辑方法:

function Edit(obj) {
debugger;
var ele = $(obj);
var url = "/Home/Edit"; // the url to the controller
var id = ele.attr('data-model-id'); // the id that's given to each button in the list
$.get(url + '/' + id, function (data) {
$('#newmodal').find(".modal-content").html(data);
$('#newmodal').modal('show');
});
};

最佳答案

首先,您对 EditorFor() 的使用没有意义,用法应该只是

 @Html.EditorFor(x => x.Name, "new { htmlAttributes = new { @class = "form-control col-md-6" } })

接下来你保存数据的脚本应该是

function btndbsave(obj) {
var ele = $(obj);
var id = ele.attr("data-model-id");
var name = $("#Name]").val();
var phone = $("#Phone").val();
var email = $("#Email").val();
var AjaxVM = { Id: id, Name: name, Phone: phone, Email: email };

$.ajax({
url: '@Url.Action("Edit", "Home")', // don't hard code your url's
dataType: "json",
data: AjaxVM,
type: "POST",
success: function (response) {
.... // see notes below
},
error: function (xhr) {
alert("error");
}
});
};

但是请注意,您的模态应包含 <form>@Html.ValidationMessageFor()为您提供客户端验证以及提交按钮的代码,以便您的脚本成为

$('form').submit(function(e) { // or give the form an id attribute and use that
e.preventDefault();
... // make ajax call
});

接下来,您的 Controller 方法只需要返回一个指示成功或其他情况的值(以及任何适用的错误消息),例如

return Json(new { success = true }); // if saved
return Json(new { success = false, message = "...." }); if not saved

注意添加一个ModelStateError没有意义,因为您没有返回 View

然后在 ajax 回调中,您更新 <td>元素成功(否则显示错误)。为此,请包含一个全局 javascript 变量来存储当前行

并将打开模式的链接更改为

<a class="edit-record" data-model-id="@item.Id" href="#" ><img src="/UserImages/pencil.png" /></a>

和脚本

var currentrow;
$('.edit-record').click(function() {
currentrow = $(this).closest('tr'); // assign the current row
... // load and display the modal
});

$.ajax({
....
success: function (response) {
if (response.success) {
// Update the current row
var cells = currentrow.find('td');
cells.eq(1).text(name);
cells.eq(2).text(phone);
cells.eq(3).text(email);
} else {
... // oops - display the message in response.message?
}
}
....
}

另请注意,无需调用 ajax 来加载模式,因为您已经在 View 中拥有所有数据。相反,包括用于编辑 AjaxVM 的 html在初始 View 中,例如,使用

@Html.Partial(""_Edit", new AjaxVM())

然后在显示模式时更新输入的值

$('.edit-record').click(function() {
currentrow = $(this).closest('tr');
var cells = currentrow.find('td');
$('#Name').val(cells.eq(1).text());
$('#Phone').val(cells.eq(2).text());
$('#Email').val(cells.eq(3).text());
$('#newmodal').modal('show');
});

关于c# - 在 Ajax-Jquery 成功时,如何在 ASP.NET MVC5 C# 中提交模态表单后替换或附加表的单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52701365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com