为什么我的JSON POST到ASP.NET Core Razor Pages Model返回null?

myzjeezk  于 12个月前  发布在  .NET
关注(0)|答案(1)|浏览(216)

这是我的JS脚本,用于将学生分数推送到页面模型。当我检查学生分数时,它具有值:

<script>
if (btnTakeScore) {
    btnTakeScore.onclick = function (e) {
        e.preventDefault();

        var rows = document.querySelectorAll('tbody tr');
        let studentScores = [];
        for (let i = 0; i < rows.length; i++) {
            let studentId = rows[i].getAttribute('studentId');

            studentScores.push({
                studentId: studentId,
                sessionId: cboSession.value,
                termId: cboTerms.value,
                classId: cboClass.value,
                subjectScores: []
            })

            let tds = rows[i].querySelectorAll('td input[type="number"]');
            for (let j = 0; j < tds.length; j++) {

                // Simulate missing score instead of a 0;
                let ctrl = tds[j];
                if (ctrl.value !== '') {

                    studentScores[i].subjectScores.push({
                        studentId: studentId,
                        subjectId: tds[j].getAttribute('subjectId'),
                        score: ctrl.value,
                        scoreTypeId: cboScoreType.value
                    });
                }
            }
        }

        // call server here to post the data
        //const serverUrl = 'https://localhost:44301/api/SaveStudentScores';
        const serverUrl = '@Url.Page("/Teacher/StudentScore")?handler=SaveScore';
        let r = new XMLHttpRequest();
        r.open('post', serverUrl);
        r.setRequestHeader('content-Type', 'application/json');
        r.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
        r.send(JSON.stringify(studentScores));
        r.onload = function () {
            if (r.status === 200) {
                var res = JSON.parse(this.responseText);
                if (res.status === true) {
                    alert(res.message);

                    // clear the fields.
                    var inputs = document.querySelectorAll('table#scoreEntry input[type="number"]');
                    inputs.forEach(d => d.value = '0'); // reset the scores to Zero

                }
            }
        }
    }
}
<script>

字符串
这是我的PageModel OnPost。当它到达这里时,scores值变为null:

public async Task<JsonResult> OnPostSaveScore([FromBody]IEnumerable<StudentScoreContainer> scores)
    {
        
        try
        {
            // Code to push date to the database 
            }

            return new JsonResult(new { status = true, messsage = "Student(s) score saved!" });
        }
        catch (Exception ex)
        {
            return new JsonResult(new { status = false, message = ex.Message });
        }

    }

 public struct StudentScoreContainer
{
    public int studentId { get; set; }
    public int classId { get; set; }
    public int sessionId { get; set; }
    public int termId { get; set; }
    public int scoreTypeId { get; set; }
    public IEnumerable<SubjectScoreContainer> subjectScores { get; set; }

}

public struct SubjectScoreContainer
{
    public int studentId { get; set; }
    public int subjectId { get; set; }
    public int score { get; set; }
}


这是我的HTML代码

<div class="card-body">
                <div class="row">
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>Class Room<span class="text-danger">* 
                           </span></label>
                            <select id="classRoom" class="select" form="searchForm" required="required" asp-items="@(new SelectList(Model.Classess, "Class.Id","Class.Name"))">
                                <option value="">Select ClassRoom</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>Session<span class="text-danger">*</span></label>
                            <select id="session" class="select" required="required" asp-items="@(new SelectList(Model.Sessions, "Id","Name"))">
                                <option value="">Select Session</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>Term<span class="text-danger">*</span></label>
                            <select id="term" class="select" required="required" asp-items="@(new SelectList(Model.Terms, "Id","Name"))">
                                <option value="">Select Term</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="form-group">
                            <label>Score Types<span class="text-danger">*</span></label>
                            <select id="cboScoreType" class="select" required="required" asp-items="@(new SelectList(Model.ScoreTypes, "Id","Name"))">
                                <option value="">Select ScoreType</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <label></label>
                        <p></p>
                        <button id="btnSearch" type="submit" class="btn btn-success btn-block"> Search </button>
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-12">
                        <div class="table-responsive">
                           
                            <table class="table table-striped custom-table table-nowrap mb-0" id="studentList">
                                <thead>
                                    <tr>
                                        <th>Student</th>
                                        @foreach (var s in Model.SubjectsByTeacher)
                                        {
                                            <th style="text-align:center">@s.Subject.Name</th>
                                        }
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach (var student in Model.Students)
                                    {
                                        <tr studentId="@student.StudentID">
                                            <td>@(student.FirstName.Trim() + " " + student.LastName.Trim())</td>
                                            @foreach (var subject in Model.SubjectsByTeacher)
                                            {
                                                <td style="text-align:center"><input type="number" min="0" max="100" class="form-control" studentId="@student.StudentID" subjectId="@subject.Subject.Id" /></td>
                                            }
                                        </tr>
                                    }
                                </tbody>
                            </table>
                            
                            <br />
                        </div>
                    </div>
                    <div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <button id="btnTakeScore" class="btn btn-primary">
                                <i class="fa fa-pen"></i> &nbsp; <b>Take Scores</b>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

vfh0ocws

vfh0ocws1#

根据你的js和razor页面代码,我发现你直接读取getAttribute值并将其发布到page方法。
由于studentId和其他属性都是int类型,但从html代码中得到的值是字符串,这就是页面模型无法很好地绑定值的原因。
我建议你可以在js中将rows[i].getAttribute('studentId')转换为int。
如下所示:
由于我没有完整的js代码和pagemodel的类,我只是创建了一个测试js模型来测试它。
你可以尝试按照下面的代码来替换你的js代码。
学生分数:

studentScores.push({
    studentId: +studentId,
    sessionId: +cboSession.value,
    termId: +cboTerms.value,
    classId: +cboClass.value,
    subjectScores: []
})

字符串
subjectScores:

studentScores[i].subjectScores.push({
    studentId: +studentId,
    subjectId: +tds[j].getAttribute('subjectId'),
    score: +ctrl.value,
    scoreTypeId: +cboScoreType.value
});


正如Joseph Ebenezer评论的那样,我们也可以使用NewtonsoftJson而不是System.Text.Json来解决这个问题:
从以下URL安装Microsoft.AspNetCore.Mvc.NewtonsoftJson软件包:https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.NewtonsoftJson
然后将此代码添加到startup.cs配置服务方法中:

services.AddRazorPages().AddNewtonsoftJson();

相关问题