我有一个WebGrid
和一个用于在PartialView
内部删除行的链接 -
@Html.ActionLink("Delete", "DeleteThis", "MyController", new { id = SelectedId }, null)
<div id="MyGrid">
@{
var grid = new WebGrid(Model.ListOfStuff, canSort: true, ajaxUpdateContainerId: "MyGrid");
@grid.GetHtml()
}
</div>
选择网格上的项目后,用户可以单击&#34;删除&#34;链接从数据库中删除行。
我的问题是,我希望在删除后调用 Ajax 调用和更新网格。我的各种工作都是以Ajax的方式工作,但我无法弄清楚如何获得&#34;删除&#34;使用Ajax。我的控制器代码如下所示 -
public ActionResult Index()
{
//CODE TO RETRIEVE THE MODEL
return PartialView("Index", model);
}
public ActionResult DeleteThis(string id)
{
////CODE TO DELETE RECORD
return RedirectToAction("Index"); // I ALSO TRIED return PartialView("Index", model) }
任何见解都将受到赞赏。谢谢!
答案 0 :(得分:0)
侦听链接的click事件,并对执行删除功能的action方法进行ajax调用。
确保您的DeleteThis
方法使用HttpPost
属性进行修饰。删除应始终为 HttpPost 操作。不是GET行动。
[HttpPost]
public ActionResult DeleteThis(string id)
{
try
{
// to do : delete
return Json(new { Status="Deleted"});
}
catch(Exception ex)
{
//log the error
return Json(new { Status="Error"});
}
}
从Action方法返回JSON。在post方法的回调中,检查Status属性值以查看删除操作是否成功。
$(function(){
$("#SelectedId").click(function(e){
e.preventDefault();
var selectedItemId=34; // you need to get this from the grid;
$.post("@Url.Action("DeleteThis","Home")/"+selectedItemId,function(data){
if(data.Status="Deleted")
{
//reload the page or just reload the partial view as needed
window.location.href=window.location.href;
// $("#GridContainer").load(@Url.Action("List","Users")");
}
});
});
});