Json发布到asp.net核心剃须刀页面模型返回null

时间:2020-10-22 03:14:50

标签: json asp.net-core asp.net-core-razor-pages

尝试了很多解决方案并在线修复,但仍未取得进展,请在研究后进行研究,我需要您的帮助

这是我的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。当它出现时,分数值将变为空

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>

请感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

根据您的js和razor页面代码,我发现您直接读取getAttribute值并将其发布到page方法。

由于studentId和other属性均为int类型,但是从html代码获得的值是字符串。这就是页面模型无法很好地绑定值的原因。

我建议您可以将rows[i].getAttribute('studentId')转换为js中的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来解决此问题。

更多详细信息,您可以参考以下代码:

从以下网址安装Microsoft.AspNetCore.Mvc.NewtonsoftJson:

https://www.nuget.org/packages/Microsoft.AspNetCore.Mvc.NewtonsoftJson

将以下代码添加到startup.cs配置服务方法中:

        services.AddRazorPages().AddNewtonsoftJson();