数据不在控制器方法 - MVC中

时间:2015-01-05 15:37:11

标签: jquery ajax asp.net-mvc asp.net-mvc-4 model-view-controller

我是MVC的新手,我正在尝试编辑一行并通过jQuery和AJAX将编辑后的数据发送到控制器方法,当我点击编辑时,特定行变为文本框和save ActionLink出现而不是edit,但是当我保存它时,它给了我一个例外。 enter image description here

这是我的jQuery / AJAX:

@model IEnumerable<OTESSystem.Models.tbl_HolidayList>

@{
    ViewBag.Title = "Index";
}


<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    <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('form').serialize();
                //var url = $(this).attr('href');
                var actionURL = '@Url.Action("Edit", "Holiday")';
                $.ajax({
                    url: actionURL,             // 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
                    success: function (html) {
                        $("#dialog-edit").dialog('open');       //
                    }
                });
            });
        });
    </script>

chtml代码:

<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>
           @* <td>
                @Html.TextBoxFor(modelItem => item.Holiday_Id, new { style = "display: none; width:170px; height:15px" })
                <div class="displaytext">
                    @Html.DisplayFor(modelItem => item.Holiday_Id)
                </div>
            </td>*@
            <td>
                @Html.TextBoxFor(modelItem => item.Holiday_Name, new { style = "display: none; width:170px; height:15px" })
                <div class="displaytext">
                    @Html.DisplayFor(modelItem => item.Holiday_Name)
                </div>
            </td>
            <td>
                @Html.TextBoxFor(modelItem => item.Holiday_Description, new { style = "display: none; width:170px; height:15px" })
                <div class="displaytext">
                    @Html.DisplayFor(modelItem => item.Holiday_Description)
                </div>
            </td>
            <td>
                @Html.TextBoxFor(modelItem => item.Holiday_date, new { style = "display: none; width:170px; height:15px" })
                <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>

控制器方法代码:

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

tbl_HolidayList.cs

namespace OTESSystem.Models
{
    using System;
    using System.Collections.Generic;

    public partial class tbl_HolidayList
    {
        public int Holiday_Id { get; set; }
        public string Holiday_Name { get; set; }
        public string Holiday_Description { get; set; }
        public Nullable<System.DateTime> Holiday_date { get; set; }
    }
}

你能告诉我为什么我得到这个例外吗?

2 个答案:

答案 0 :(得分:1)

之前你问了一个类似的问题,主要问题是和以前一样的问题。您不能将foreach循环与@Html.TextBoxFor等一起使用。您需要使用for循环并对表达式建立索引:

问题1:

e.g。

@for (int i = 0; i < Model.Count(); i++)
{
     [snip]
     <td>
          @Html.TextBoxFor(m => Model[i].Holiday_Name, new { style = "display: none; width:170px; height:15px" })
          <div class="displaytext">
             @Html.DisplayFor(m => Model[i].Holiday_Name)
          </div>
     </td>
     [snip]
}

问题是传递给TextBoxFor的表达式树需要知道索引值才能正确生成索引名称。 foreach提供的局部变量不知道它在父集合中的位置。

问题2

另一个问题是您只想将一行发送回Edit方法。这与上述建议不一致。

尝试将单行序列化,然后不正确的元素命名应该对您有利:

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

其他问题

您的网页目前需要IEnumerable<OTESSystem.Models.tbl_HolidayList>个项目集合。 您通常会使用for循环渲染这些循环(不是每个循环 - 请参阅问题1)。然后,您将回发整个页面,以便edit方法也应使用IEnumerable<OTESSystem.Models.tbl_HolidayList>

e.g。

 public ActionResult Edit(IEnumerable<tbl_HolidayList> tbl_holidaylist)
 {
      foreach( var holiday in tbl_holidaylist)
      {
          //save changes
      }
 }

基本上,您的页面中存在两个相互矛盾的事情。您需要决定是采用标准MVC实践还是反对它们:)

答案 1 :(得分:0)

这对我有用

<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>