简体   繁体   中英

how to consume JSon object from a Razor page that has no headerID's in C# MVC5 Controller

I have used this javascript to convert a WebGrid (C# MVC5) - I am not sure how to consume the json object which has no headers. Here is my WebGrid creation script:

 var grid = new WebGrid(

            rowsPerPage: 50,
            canPage: true,
            canSort: true,
            ajaxUpdateContainerId: "gridcontent");

grid.Bind(
            source: Model,
            autoSortAndPage: true,
            rowCount: Model.Count()
            );

        <div id="gridcontent">
            @grid.GetHtml(
        htmlAttributes: new
        {
            @id = "WebGrid",
            @class = "searchGridView"

        },
             fillEmptyRows: false,
             mode: WebGridPagerModes.All,
             columns: new[] {
            grid.Column(columnName:"ID",header: "Attendee ID", canSort: false),
            grid.Column( columnName:"LName", header:"Last Name"),
            grid.Column( columnName: "FName", header: "First Name"),
            grid.Column("Title"),
            grid.Column("kOrgID", "Org ID"),
            grid.Column("Organization"),
            grid.Column("UpdatedOn","Last Used",format: (item) => string.Format("{0:MMM yyyy}",item.UpdatedOn)),
            grid.Column("City"),
            grid.Column("State"),
            grid.Column("LegalApprovedAtt", "Approve?",
                    format: @<text><input name="Approve"
                                          type="checkbox" value="@item.LegalApprovedAtt" /></text> ),
            grid.Column("",
                header: "Actions",
                format: @<text>
                    @Html.ActionLink("Edit", "Edit" ,new { id=item.ID }) |
                    @Html.ActionLink( "Details","Details", new { id=item.ID })

                </text>
                )
     })
        </div>

So I get the following table (note: no header ID's):

<table id="WebGrid" class="searchGridView" data-swhgajax="true" data-swhgcontainer="gridcontent" data-swhgcallback="">
    <thead>
        <tr>
            <th scope="col">
Attendee ID            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=LName&amp;sortdir=ASC">Last Name</a>            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=FName&amp;sortdir=ASC">First Name</a>            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=Title&amp;sortdir=ASC">Title</a>            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=kOrgID&amp;sortdir=ASC">Org ID</a>            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=Organization&amp;sortdir=ASC">Organization</a>            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=UpdatedOn&amp;sortdir=ASC">Last Used</a>            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=City&amp;sortdir=ASC">City</a>            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=State&amp;sortdir=ASC">State</a>            </th>
            <th scope="col">
<a data-swhglnk="true" href="/Attendees/Modified?sort=LegalApprovedAtt&amp;sortdir=ASC">Approve?</a>            </th>
            <th scope="col">
Actions            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>6146</td>
            <td>Kimmel</td>
            <td>Jimmy</td>
            <td>General Funny Guy</td>
            <td>277</td>
            <td>Unite</td>
            <td>Jun 2019</td>
            <td></td>
            <td></td>
            <td><input name="Approve"
                                          type="checkbox" /> </td>
            <td>
<a href="/Attendees/Edit/6146">Edit</a> |
<a href="/Attendees/Details/6146">Details</a>


</td>
        </tr>
 </tbody>
    </table>

I am converting this table to a JSON object using the following javascript:

<script>
    function gridTojson() {
        var json = '{';
        var otArr = [];


        var tbl2 = $('#WebGrid tbody tr').each(function (i) {
            if ($(this)[0].rowIndex != 0) {
                x = $(this).children();
                var itArr = [];
                //I tried to add the header text here to no avail
                //var tdIndex = x.index() + 1;
                //var $th = $('#WebGrid tr').find('th:nth-child(' + tdIndex + ')');
                x.each(function () {
                    if ($(this).children('input').length > 0) {
                        var checked = $(this).children('input:checked').length
                        //alert(checked);
                        if (checked != 0) { itArr.push('"1"'); }
                        else { itArr.push('"' + $(this).children('input').val() + '"'); }
                    }
                    else {
                       // alert($(this).parents("th").val());
                       // itArr.push('"' + $(this).parents("th").val() + '":');
                        itArr.push('"' + $(this).text() + '"');
                    }
                });
                otArr.push('"' + i + '": [' + itArr.join(',') + ']');
            }
        })
        json += otArr.join(",") + '}'
        return json;
    };





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

   </script>

And I get this json object (with no headers as there are no header ID's due to the webgrid (which is great for formatting and ease of setup, but I guess I'm paying for that now...

I do not know how to consume the json object in my controller (the " 1 before \\nEdit |" indicates that the checkbox is checked:

"{\"0\": [\"6146\",\"Kimball\",\"Jimmy\",\"General Funny Guy\",\"277\",\"Unite\",\"Jun 2019\",\"\",\"\",\"1\",\"\nEdit |\nDetails\n\n                \n\"],\"1\": [\"6147\",\"Hawk\",\"Jack\",\"\",\"547\",\"Painters\",\"Jun 2019\",\"\",\"\",\"on\",\"\nEdit |\nDetails\n\n                \n\"]}"

I finally sorted this one out..If there is a more dynamic answer, or a better way to do this, please let me know! Thanks in Advance.

if(ModelState.IsValid)
{
    try
    {

        Dictionary <string,string[]> log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);

        foreach (KeyValuePair<string,string[]> keyValue in log)
        {
            if (keyValue.Value[9] == "1")//Update this row based on the checkbox being checked
            {
                var AttendeeID = keyValue.Value[0];
                int intAttendeeID = 0;
                if (int.TryParse(AttendeeID, out intAttendeeID))//Make sure the AttendeeID is valid
                {
                    var LName = keyValue.Value[1];
                    var FName = keyValue.Value[2];
                    var Title = keyValue.Value[3];
                    var kOrgID = keyValue.Value[4];
                    var Org = keyValue.Value[5];
                    var City = keyValue.Value[7];
                    var State = keyValue.Value[8];
                    var LegalApproval = keyValue.Value[9];


                    tblAttendee att = db.tblAttendees.Find(Convert.ToInt32(AttendeeID));
                    att.FName = FName;
                    att.LName = LName;
                    att.Title = Title;
                    att.kOrgID = Convert.ToInt32(kOrgID);
                    att.Organization = Org;
                    att.City = City;
                    att.State = State;
                    att.LegalApprovedAtt = Convert.ToBoolean(LegalApproval);
                }
            }
        }
        db.SaveChanges();

    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

You can avoid assigning the var's and just populate the att object with the KeyValue.Value[n] value, but you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM