-1

I am new in MVC and I am working on project in which I have a Gridview showing data, when I click Edit specific row becomes textboxes and Edit becomes Save, I edit the data and click Save, control goes in a jQuery function which sends the edited row data to the controller method using AJAX, I put an alert to see tha data which gives me this string enter image description here

and null is going to my controller method and I get an exception enter image description here

my jQuery/Ajax Code:

<script type="text/javascript">
        $(document).ready(function () {
            function toggleEditability() {
                $(this).closest('tr')
                       .find('a.Edit, a.Save, .displayText, input[type=text]')
                       .toggle();

            }

            $('a.Edit').click(toggleEditability);

            $('a.Save').click(function () {;
                toggleEditability.call(this);



                var data = $(this).closest('tr').find('input').serialize();      
                alert(data);          
                $.ajax({
                    url: '@Url.Action("Edit", "Holiday")',             // Url to send request to
                    data: data,           // Send the data to the server
                    type: "Post",         // Make it a POST request
                    dataType: "html",     // Expect back HTML
                    //contentType: 'application/json; charset=utf-8',
                    success: function (html) {
                        alert(html);
                        console.log(html);
                    },
                    error: function () {
                        alert("error");
                    }
                });
            });
        });
    </script>

chtml Code:

<div id="details">
    <table>
        <tr>
            @*<th>
                @Html.Label("ID")
            </th>*@
            <th>
                @Html.Label("Name")
            </th>
            <th>
                @Html.Label("Description")
            </th>
            <th>
                 @Html.Label("Date")
            </th>
            <th></th>
        </tr>

    @foreach (var item in Model)
    {
        if (Convert.ToDateTime(item.Holiday_date).Year.ToString() == DateTime.Now.Year.ToString())
        {
            <tr>
                @Html.HiddenFor(modelItem => item.Holiday_Id)
            @*<td>
                 @Html.DisplayFor(modelItem => item.Holiday_Id)
                 @Html.HiddenFor(modelItem => item.Holiday_Id)
            </td>*@
            <td>
                <div class="HolidayName">
                    @Html.TextBoxFor(modelItem => item.Holiday_Name,  new { id = "txtname", name="HolidayName", style = "display: none; width:170px; height:15px" })
                </div>
                <div class="displaytext">
                    @Html.DisplayFor(modelItem => item.Holiday_Name)
                </div>
            </td>
            <td>
                <div class="HolidayDescription">
                    @Html.TextBoxFor(modelItem => item.Holiday_Description, new { id = "txtdesc", name="HolidayDescription", style = "display: none; width:170px; height:15px" })
               </div>
               <div class="displaytext">
                    @Html.DisplayFor(modelItem => item.Holiday_Description)
                </div>
            </td>
            <td>
                <div class="HolidayDate">
                    @Html.TextBoxFor(modelItem => item.Holiday_date, new { id = "txtdate", name="HolidayDate", style = "display: none; width:170px; height:15px" })
                </div>
                <div class="displaytext">
                    @Html.DisplayFor(modelItem => item.Holiday_date)
                </div>
            </td>
            <td>
               @Html.ActionLink("Edit", "Edit", new { id = item.Holiday_Id }, new { @class = "Edit", Href="#" })
               @Html.ActionLink("Save", "Save", new { id = item.Holiday_Id}, new { @class = "Save", Href = "#", style = "display:none" } ) |
               @Html.ActionLink("Delete", "Delete", new { id = item.Holiday_Id }, new { @class = "lnkDelete" })
               @Html.ActionLink("Cancel", "Cancel", new { id = item.Holiday_Id}, new { @class = "Cancel", Href = "#", style = "display:none" } )
            </td>
        </tr>
        }

    }

    </table>

   </div>

and my controller method code is:

[HttpGet]
        public ActionResult Edit(int id = 0)
        {
            tbl_HolidayList tbl_holidaylist = db.tbl_HolidayList.Find(id);
            if (tbl_holidaylist == null)
            {
                return HttpNotFound();
            }
            return PartialView(tbl_holidaylist);
        }

        //
        // POST: /Holiday/Edit/5

        [HttpPost]
        public ActionResult Edit(tbl_HolidayList tbl_holidaylist)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tbl_holidaylist).State = EntityState.Modified;
                db.SaveChanges();//save changes
                TempData["Msg"] = "Data has been updated succeessfully";
                return RedirectToAction("Index");
            }
            return PartialView(tbl_holidaylist);
        }

my question is that how can I retrieve my specific information from that string in data so my controller method could get that as parameter??

2 Answers2

1

Your control names do not match our property names (for example your tbl_holidaylist has property name Holiday_Name but your posting back a value for the key item.Holiday_Name). Your are also generating invalid html (duplicate id attributes for each row).

Instead of

var data = $(this).closest('tr').find('input').serialize();

Use

var inputs = $(this).closest('tr').find('input');
var id = inputs.eq(0).val();
var name = inputs.eq(1).val();
var description = inputs.eq(2).val();
var date = inputs.eq(3).val();
var data = { Holiday_Id: id, Holiday_Name: name, Holiday_Description: description, Holiday_date: date };
....

I also recommend you change the html attributes of @Html.TextBoxFor() methods from

@Html.TextBoxFor(modelItem => item.Holiday_Name,  new { id = "txtname", name="HolidayName", style = "display: none; width:170px; height:15px" })

to

@Html.TextBoxFor(modelItem => item.Holiday_Name,  new { id = "" })

which will remove the id attribute. Then use css to handle the style rather than inline formatting

table input {
  display: none;
  width:170px;
  height:15px;
}
-1

I made these changes which fixed my problem

<script type="text/javascript">
        $(document).ready(function () {
            function toggleEditability() {
                $(this).closest('tr')
                       .find('a.Edit, a.Save, .displayText, input[type=text]')
                       .toggle();

            }

            $('a.Edit').click(toggleEditability);

            $('a.Save').click(function () {;


                //alert("hello");
                var tr = $(this).parents('tr:first');
                //alert(tr);
                var hid = tr.find("#hdnid").val();
                var HName = tr.find("#txtname").val();
                var Hdesc = tr.find("#txtdesc").val();
                var date = tr.find("#txtdate").val();
                tr.find("#hdnid").text(hid);
                tr.find("#txtname").text(HName);
                tr.find("#txtdesc").text(Hdesc);
                tr.find("#txtdate").text(date);
                toggleEditability.call(this);
                //tr.find('.edit-mode, .display-mode').toggle();
                //alert(hid);
                //alert(HName);
                //alert(Hdesc);
                //alert(date);
                var dataToSend = {
                    Holiday_Id: hid,
                    Holiday_Name: HName,
                    Holiday_Description : Hdesc,
                    Holiday_date: date
                }
                var url = '@Url.Action("Edit", "Holiday")';
                //alert("b4 ajax");
                $.ajax({
                    url: '@Url.Action("Edit", "Holiday")',
                    type: "Post",
                    data: dataToSend,
                    //dataType: "html",
                    success: function (data) { 
                        alert("saved");
                    },
                    error: function () {
                        alert("error");
                    }
                });
            });
        });
    </script>