如何在MVC3 Razor的Webgrid上实现编辑和删除?

时间:2012-08-22 05:41:04

标签: asp.net-mvc razor webgrid

下面我给出了控制器,型号和视图。运行后,网格显示值,但我需要编辑值并删除同一页面上的值。我搜索并看到了一些示例,在编辑中,删除它们创建单独的索引但我需要的是编辑和删除应该在同一页面而不是另一页面上完成。请给我一个解决方案。

控制器:

public ActionResult Index()
        {
            var PersonList = new List<Person>()
            {
            new Person(){Name="A", Age=20,Id =1},
            new Person(){Name="B",Age=45,Id =2},
            new Person(){Name="C", Age=30,Id =3},
            new Person(){Name="D",Age=55,Id =4},
            new Person(){Name="E", Age=30,Id =5},
            new Person(){Name="F",Age=25,Id =6},
            new Person(){Name="G", Age=30,Id =7},
            new Person(){Name="H",Age=25,Id =8},
            };

            return View(PersonList);
        }

班级:

public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

查看:

@model IEnumerable<edit.Models.Person>

@{
    ViewBag.Title = "Index";
}

<html>
<head>
<title>Index</title>
<style type="text/css">
.webGrid { margin: 4px; border-collapse: collapse; width: 300px; }
.header { background-color: #E8E8E8; font-weight: bold; color: #FFF; }
.webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
.alt { background-color: #E8E8E8; color: #000; }
.person { width: 200px; font-weight:bold;}
</style>
</head>
<body>
@{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5);
grid.Pager(WebGridPagerModes.NextPrevious);
@grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Name", "Given Name", canSort: true, format:@<b>@item.Name</b>, style: "person"),
grid.Column("Age", "How Old?", canSort: true)
));
}
</body>
</html>

4 个答案:

答案 0 :(得分:5)

@Yasser,通过GET链接实现DELETE非常危险。抓取页面的搜索引擎可能会删除您的所有信息。

实现POST操作要好得多。这是一个例子:

在视图中:

@functions{
  string Delete(dynamic p)
  {
    string actionController = Url.Action("Delete", "Admin", new {id=p.AccountId});
    return "<form style='display:inline;' method='post' action='" + actionController + "'><input type='submit' value='Delete' onclick=\"return confirm('Are you sure?')\"/></form>";
  }
}

...
grid.Column(header: "", format: p => Html.Raw(Delete(p)))

在控制器中:

[HttpPost]
public ActionResult Delete(int id)
{
   PerformDelete(id);
   return RedirectToAction("Index");
}

答案 1 :(得分:3)

这是你可以开始的事情,

您必须首先生成两个名为“编辑”和“删除”的操作链接以及网络网格中的每条记录。

请参阅this tutorial

类似这样的事情

grid.Column(format: (item) => Html.ActionLink("Edit", "ActionName", new { param1 = "send id here", param2 = "xtra param" }))
grid.Column(format: (item) => Html.ActionLink("Delete", "ActionName2", new { param1 = "hello", param2 = "bye" }))

希望这有帮助。

答案 2 :(得分:2)

答案 3 :(得分:1)

您可以使用asp.net mvc和knockoutjs尝试使用内联可编辑网格视图: www.anhbui.net/blog?id=kojs-1

相关问题