从JsonResult检索对象列表并发送到数据库

时间:2014-07-24 15:43:53

标签: c# jquery asp.net-mvc json

我在表格中显示一个由dropdownbox .change函数触发的对象数据列表。但是,我还需要将此数据提交到数据库。到目前为止,我可以在下拉列表更改时显示数据,但是我无法检索对象列表并在提交时将它们发送到数据库。

您会注意到视图模型中的一个属性是布尔值。这用于检查哪些学校被发送到数据库。

此处显示的最后一个方法在提交时调用。当我检查发送给它的值时(通过tmpModel参数),Schools列表为空。如何使用选中的学校填充此列表?

首先,这是我的视图模型中的类,它包含我想要显示和提交的数据。

public class School { public int? SchoolId { get; set; } public string SchoolName { get; set; } public string TownName { get; set; } public bool isMoving { get; set; } }

接下来,这是我用来获取学校列表的JsonResult方法。

ReorganizationVm model = new ReorganizationVm(); // an instance of my view model
    public JsonResult Schools(int townCode, int sauId, int fiscalYear)
    {
        using (var service = new ParameterService(this.User))
        {
            try
            {
                model.Schools = new List<School>();
                foreach (var o in service.GetSchools(townCode, sauId, fiscalYear))
                {
                    School School = new School
                    {
                        SchoolId = o.School_ID,
                        SchoolName = o.SchoolName,
                        TownName = o.TownName,
                        isMoving = false
                    };
                    model.Schools.Add(School);
                }

                return Json(model.Schools, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

            }
            return Json(null);
        }
    }

这是从函数中调用控制器方法和表的JavaScript函数。

<script type="text/javascript">
    $(function () {

        $('#CurrentSau_SauId').change(function () {
            var sauId = $("#CurrentSau_SauId").val();
            var townCode = $("#Town_TownCode :selected").val();
            var fiscalYear = $("#FiscalYear").val();
            var schools = $("#schools");
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.Action("Schools", "Reorganization"))",
                data: { "sauId" : sauId, "townCode" : townCode, "fiscalYear" : fiscalYear },
                success: function (data) {
                    var result = "";
                    schools.html('');
                    $.each(data, function (id, school) {
                        result +=   '<tr><th>Select Schools that are Moving to New SAU</th></tr>' +
                                    '<tr><th>School Name</th><th>Town</th><th>Moving to New SU</th></tr>' +
                                    '<tr><td>' + school.SchoolName + '</td><td>' + school.TownName + '</td><td>' +
                                    '<input type="checkbox"></td></tr>';
                    });
                    schools.html(result);
                },
                error: function (xhr, AJAXOptions, thrownError) {
                    alert('Failed to retrieve schools.');
                }
            });        
        });
    });
</script>

<table id="schools">

</table>
<table>
    <tr>
        <td>
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table>

最后,提交时调用的控制器方法。现在,它是空的,因为我只是用它来检查哪些值正在恢复。

public ActionResult Index(ReorganizationVm tmpModel)
{
    return View();
}

修改:更新*

已经有一段时间了,但我终于有时间回到这里了。在尝试了AmanVirdi发布的代码后,我发现它无效。但是,我能够通过向html添加值属性来使其工作(大多数情况下)。这是构建要注入页面的html的Jquery。另请注意,id变量已更改为i,而不是使用html()来注入我现在使用append()的html。

JQuery

            $.each(data, function (i, school) {
                result +=
                    '<tr><td>' + school.SchoolName +
                    '<input type="hidden" name="SchoolList[' + i + '].SchoolName" id="SchoolList[' + i + ']_SchoolName" />' +
                    '<input type="hidden" name="SchoolList[' + i + '].SchoolId" value="' + school.SchoolId + '" /></td>' +

                    '<td>' + school.Town +
                    '<input type="hidden" name="SchoolList[' + i + '].Town" value="' + school.Town + '" /></td>' +

                    '<td><input type="checkbox" name="SchoolList[' + i + '].IsMoving" value="' + school.SchoolId + '" />';

$("#schools").append(result);

如上所述,它在很大程度上起作用。所有值都将发送到控制器,但 isMoving复选框值对于生成列表中的每个对象保持为false。

如何根据是否检查了checbox来更改isMoving值?我正在阅读CheckBoxListFor并认为它可能对我有帮助,但我直接生成html而不是使用Html助手。也许我可以复制CheckBoxListFor生成的html。这是要走的路吗?

1 个答案:

答案 0 :(得分:0)

你需要为&#34;学校&#34;中的每个属性添加四个隐藏字段。模型类,在&#34;结果&#34;串。像这样:

**的jQuery:**试验[位置] .Test.Preconditions&#34;

result +='<tr><th>Select Schools that are Moving to New SAU</th></tr>' +
         '<tr><th>School Name</th><th>Town</th><th>Moving to New SU</th></tr>' +
         '<tr><td><input type="hidden" id="SchoolList['+ id +']_SchoolId" name="SchoolList['+ id +'].SchoolId" />' +
         '<input type="hidden" id=""SchoolList['+ id +']_SchoolName" name="SchoolList['+ id +'].SchoolName" />'+school.SchoolName + '</td>' +
         '<td><input type="hidden" id="SchoolList['+ id +']_TownName" name="SchoolList['+ id +'].TownName" />' + school.TownName +'</td>' +
         '<td><input type="checkbox" id="SchoolList['+ id +']_isMoving" name="SchoolList['+ id +'].isMoving" checked="checked"/></td></tr>';

<强> HTML

<form action="Controller/Index" method="get">
<!-- <form action="Controller/SaveData" method="get"> for SaveData method -->
  <table id="schools">

  </table>
  <table>
    <tr>
        <td>
            <input type="submit" value="Submit"/>
        </td>
    </tr>
</table>

<强>控制器 并在Index方法中添加[HttpPost]:

[HttpPost]
public ActionResult Index(ReorganizationVm tmpModel)
{
    return View();
}

或者您可以创建单独的操作方法来保存学校数据。

[HttpPost]
public ActionResult SaveData(ReorganizationVm tmpModel)
{
    // do your stuff here
    return View("Index");
}

更改您的模型,如下所示:

public class ReorganizationVm()
{
    public List<Schools> SchoolList { get; set; }
}


ReorganizationVm model = new ReorganizationVm(); // an instance of my view model
    public JsonResult Schools(int townCode, int sauId, int fiscalYear)
    {
        using (var service = new ParameterService(this.User))
        {
            try
            {
                model.Schools = new List<School>();
                foreach (var o in service.GetSchools(townCode, sauId, fiscalYear))
                {
                    School School = new School
                    {
                        SchoolId = o.School_ID,
                        SchoolName = o.SchoolName,
                        TownName = o.TownName,
                        isMoving = false
                    };
                    model.Schools.Add(School);
                }

                return Json(model, JsonRequestBehavior.AllowGet); //pass whole model variable
            }
            catch (Exception ex)
            {

            }
            return Json(null);
        }
    }