MVCContrib网 - 如何添加和使用Ajax删除行?
-
27-09-2019 - |
题
我不知道什么是在MVCContrib生成网格删除行的最佳策略。
考虑此网格:
Html.Grid(Model.Proc.Documents).Columns(column =>
{
column.For(c => c.Name).Named("Title");
column.For(c => c.Author.Name).Named("Author");
column.For("Action").Action(
delegate(DocumentDto doc)
{
const string cbxFrmt =
"<td><strong><a href=\"#\" onclick=\"DocDetails({0})\">View details</a></strong> | " +
"<strong><a href=\"#\" onclick=\"RemoveDoc({1})\">Delete</a></strong>" +
"</td>";
Response.Write(string.Format(cbxFrmt, doc.Id, doc.Id));
}
).DoNotEncode().Named("Action");
})
.Attributes(id => "documentgrid"));
每个行具有调用RemoveDoc(文档ID)javascript函数,其中I应该调用在控制器的动作为实际上移除在数据模型中,这是相当容易的文档中删除的行的链接,但然后我不如何从TBODY使用jQuery删除行。请指教。我是一个complitely错误的轨道?什么是做到这一点的最好方法是什么?
和有关添加一行。起初我还以为莫名其妙地做这样的:
function UploadDocument() {
var action = '<%=Html.BuildUrlFromExpression<MyController>(c => c.UploadDocument(parameters))%>';
$.ajax({
type: "POST",
url: action,
data: { data to upload },
cache: false,
dataType: 'text',
success: function (data, textStatus) {
var newRow = "<tr class='gridrow'><td>" + v1 +
"</td><td>" + doc_author + "</td>" +
"<td><strong><a href=\"#\" onclick=\"DocDetails(doc_id_returned_by_ajax)\">View details</a></strong> | " +
"<strong><a href=\"#\" onclick=\"RemoveDoc(doc_id_returned_by_ajax)\">Delete</a></strong>" +
"</td>" +
"</tr>";
var docgrid = $('#documentgrid');
var tbody = $("table[class='grid']>tbody");
$(tbody).append(newRow);
},
error: function (xhr, textStatus, errorThrown) {
var msg = JSON.parse(xhr.responseText);
alert('Error:' + msg.Message);
}
});
}
但我不知道这是做的最好的做法。任何其他策略?
谢谢!
解决方案
的线中也许一些:
<%= Html.Grid<Document>(Model.Proc.Documents)
.Columns(column => {
column.For(c => c.Name).Named("Title");
column.For(c => c.Author.Name).Named("Author");
column.For("TableLinks").Named("");
})
%>
和在TableLinks.ascx
:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeNs.Document>" %>
<td>
<% using (Html.BeginForm<HomeController>(c => c.Destroy(Model.Id))) { %>
<%= Html.HttpMethodOverride(HttpVerbs.Delete) %>
<input type="submit" value="Delete" />
<% } %>
</td>
和在控制器:
[HttpDelete]
public ActionResult Destroy(int id)
{
Repository.Delete(id);
return RedirectToAction("Index");
}
正如你可以看到我使用一个标准的形式提交按钮来删除。如果你想使用AJAX它是很容易生成一个简单的链接,连接到单击事件使用jQuery,你在你的例子一样:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeNs.Document>" %>
<td>
<%= Html.ActionLink(
"Delete document",
"Destroy",
new { id = Model.Id },
new { @class = "destroy" }
) %>
</td>
和最后逐步提高的链接:
$(function() {
$('.destroy').click(function() {
$.ajax({
url: this.href,
type: 'delete',
success: function(result) {
alert('document successfully deleted');
}
});
return false;
});
});
可以看到在此示例项目动作那些概念。
不隶属于 StackOverflow