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

本文关键字:并发 数据库 列表 对象 JsonResult 检索 | 更新日期: 2023-09-27 18:14:43

我在一个由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。

我怎样才能得到isMoving值根据复选框是否被选中而改变?我正在阅读关于CheckBoxListFor,并认为它可能会帮助我,但我直接生成的html,而不是使用html助手。也许我可以复制由CheckBoxListFor生成的html。是这条路吗?

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

您需要在"result"字符串中为"Schools"模型类中的每个属性添加四个隐藏字段。这样的:

jQuery:

* * * *测试(位置).Test.Preconditions"

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

<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);
        }
    }