![](/img/trans.png)
[英]How can I reformat my ASP.NET MVC5 error messages to show only the first message in C#
[英]On the success of Ajax-Jquery how can I Replace or Append the cell values of table after the submission of Modal form in ASP.NET MVC5 C#
當模態表單提交並成功關閉時,數據會更新到我的數據庫表中,但我需要的是沒有頁面刷新數據應該在表的單元格中更新。
我是 JQuery 的新手,如果有人向我解決這個問題,我將不勝感激。
這是我放在局部視圖末尾的腳本:
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");
}
});
};
作為模態的部分視圖:
<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">×</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>
這是控制器:
[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
});
接下來,您的控制器方法只需要返回一個指示成功或其他情況的值(如果適用,還需要返回任何錯誤消息),例如
return Json(new { success = true }); // if saved
return Json(new { success = false, message = "...." }); if not saved
請注意,添加ModelStateError
沒有意義,因為您沒有返回視圖
然后在 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 調用來加載模式,因為您已經擁有視圖中的所有數據。 相反,在初始視圖中包含用於編輯AjaxVM
的 html,例如,使用
@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');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.