asp.net-mvc - 通过 post asp.net mvc 将 webgrid 数据传递回 Controller

标签 asp.net-mvc webgrid

我是 MVC 新手,想知道如何使用 View 模型在单击提交按钮时立即将整个网格数据提交到 Controller 。

在 View 中

@model prjMVC4Training.Models.BookViewModel
@{
    ViewBag.Title = "Index";
    var categories = ViewBag.BookCategories;
    var authors = ViewBag.BookAuthors;
    var grid = new WebGrid(source: Model.BookData, canSort: true, canPage:true);    
}

@using (Html.BeginForm("BookPost", "Book", FormMethod.Post, new { @id = "grid" }))
{
    <h2>Book Index Page</h2>    
    @Html.HiddenFor(m => m.PrimaryKeyID)

    @grid.GetHtml(
        tableStyle: "table",
        alternatingRowStyle: "alternate",
        selectedRowStyle: "selected",
        headerStyle: "header",
        columns: grid.Columns(
            grid.Column("Actions",
                style: "col1",
                canSort: false,
                format: @<text>
                    <button type="button"  class="edit-book display-mode" id="@item.BookID">Edit</button>
                    <button type="button" class="save-book edit-mode" id="@item.BookID">Save</button>
                    <button type="button" class="cancel-book edit-mode" id="@item.BookID">Cancel</button>
                    </text>),
                grid.Column("BookTitle",
                    style: "col2",
                    canSort: true,
                    format: @<text>
                        <span id="dBookTitle" class="display-mode">@item.BookTitle</span>
                        @Html.TextBox("BookData_" + (int)item.BookID + "__BookID", (string)item.BookTitle, new { @class = "edit-mode", size = 45 })
                        </text>),
                grid.Column("AuthorName",
                    header: "Author",
                    style: "col3",
                    canSort: true,
                    format: @<text>
                        <span id="dAuthorName" class="display-mode">@item.AuthorName</span>
                        @Html.DropDownList("AuthorID_" + (int)item.BookID, (ViewBag.BookAuthors as SelectList).Select(option => new SelectListItem
                        {
                            Text = option.Text,
                            Value = option.Value,
                            Selected = option.Value == @item.AuthorID
                        }), new { @class = "edit-mode" })
                        </text>),
                grid.Column("CategoryName",
                style: "col4",
                canSort: true,
                    format: @<text>
                        <span id="dCategoryName" class="display-mode">@item.CategoryName</span>
                        @Html.DropDownList("CategoryID_" + (int)item.BookID, (ViewBag.BookCategories as SelectList).Select(option => new SelectListItem
                        {
                            Text = option.Text,
                            Value = option.Value,
                            Selected = option.Value == @item.CategoryID
                        }), new { @class = "edit-mode" })
                        </text>),
                grid.Column("BookISBN",
                    style: "col5",
                    format: @<text>
                        <span id="dBookISBN" class="display-mode">@item.BookISBN</span>
                        @Html.TextBox("BookISBN_" + (int)item.BookID, (string)item.BookISBN, new { @class = "edit-mode", size = 20 })
                        </text>),
                grid.Column("IsMember",
                    style: "",
                    format: @<text>
                        <span id="dMember" class="display-mode">@item.IsMember</span>
                        <input type="checkbox" id="MemberID_" + (int)item.BookID name="MemberID" @(item.IsMember == true ? "Checked" : null) class="edit-mode"/>
                        </text>)))    
    <button type="submit" value="Save Book Data">Save Book Data</button>
}

在提交按钮上,我想将值传递给 Controller ​​

[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BookPost(BookViewModel obj)
{
    ViewBag.BookCategories = new SelectList(BookHelperData.GetBookCategories(), "CategoryID", "CategoryName", "20");
    ViewBag.BookAuthors = new SelectList(BookHelperData.GetAuthors(), "AuthorID", "AuthorName");
    //ViewBag.BookAuthors = BookHelperData.GetAuthorsList();
    var Book = BookHelperData.GetBooks();
    return View(Book);

}

我的ViewModel类是这样的-

public class BookViewModel
{
    public int PrimaryKeyID { get; set; }
    public List<Book> BookData { get; set; }
}

最佳答案

您可以编写一个通用方法,循环网格中的所有数据并将其转换为 json 结构。

function gridTojson() {
        var json = '{';
        var otArr = [];
        var tbl2 = $('#employeeGrid tbody tr').each(function (i) {
            if ($(this)[0].rowIndex != 0) {
                x = $(this).children();
                var itArr = [];
                x.each(function () {
                    if ($(this).children('input').length > 0) {
                        itArr.push('"' + $(this).children('input').val() + '"');
                    }
                    else {
                        itArr.push('"' + $(this).text() + '"');
                    }
                });
                otArr.push('"' + i + '": [' + itArr.join(',') + ']');
            }
        })
        json += otArr.join(",") + '}'
        return json;
    }

现在点击提交按钮,您需要将数据传递给 Controller ​​。

$('#btnsave').click(function (e) {
        //debugger;
        var _griddata = gridTojson();
        var url = '@Url.Action("UpdateGridData")';
            $.ajax({
                url: url,
                type: 'POST',
                data: { gridData: _griddata }
            }).done(function (data) {
                if (data != "") {
                    $('#message').html(data);
                }
            });
     });

现在在 Controller 上将数据序列化回来

public ActionResult UpdateGridData(string gridData)
        {
            var log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);     
            return Json("Update Successfully");
        }

这是post关于这一点。

关于asp.net-mvc - 通过 post asp.net mvc 将 webgrid 数据传递回 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21848322/

相关文章:

asp.net-mvc - 将文件附加/上传到尚未保存的注释 - 对此的最佳策略是什么?

asp.net-mvc - Razor 嵌套 WebGrid

asp.net-mvc - 在 aspx 页面中的 webgrid 中从一页导航到另一页时丢失 Web 控件数据

asp.net-mvc-3 - MVC3 WebGrid 页面/排序问题与页面其他地方的复选框

c# - 不能多次枚举查询的结果 (C#)( Entity Framework )(存储过程)

c# - ASP.Net MVC 创建注册错误

c# - Webgrid 分页和排序不起作用

c# - Razor webgrid ajax 分页和排序

c# - ASP.NET Core 自定义验证创建模型的新实例

asp.net-mvc - 使用 ViewModel 屏蔽可为 null 的域属性