Передача массива в формате json и доступ к нему в контроллере mvc

#json #asp.net-mvc-3

#json #asp.net-mvc-3

Вопрос:

я пытаюсь создать массив marklistdetails для публикации сведений о нескольких студентах, я не могу получить доступ к нему на контроллере, который выдает ошибку, поскольку объект не инициализирован

json-код

var MarksEntry = { Adm_Or_Name: «, AdmissionNo: «, Name: «, ClassId: «, ClassSectionId: «, RollNo: «, MarksEntered: «, RemarksEntered: «, Subjectid: «, ExaminationID: «, ExamDate: «, Present: «, MarksEntryDetails: [] mvc 3 — Передача массива в формате json и доступ к нему в контроллере mvc — Stack Overflow,

 };
var MarksEntryDetails =
  {
    //  StudentId: '',
      MarksEntered: '',
     // RemarksEntered: '',
     // Total_Oral_Marks: '',
     // TOTAL_PRACTICAL_MARKS: '',
      //TOTAL_PROJECT_MARKS: '',
      //TOTAL_MARKS: '',
     // PRESENT: '',
    //  PASS_FAIL: '',


    };

function SavingRecords(url) {
    var result = 0;
    var Index = 0;
    //var marksEntrylist = [];
    MarksEntry.ClassSectionId = $("table#IntialDetails tr").find("td").eq(6).html()
    MarksEntry.ExaminationID = $("table#IntialDetails tr").find("td").eq(7).html()
    MarksEntry.Subjectid = $("table#IntialDetails tr").find("td").eq(8).html()
    $('table#student_marks tr').each(function () {

        MarksEntry.MarksEntryDetails.add(new CreateMarksEntry(this));
        console.log(MarksEntry.MarksEntryDetails);
        $.getJSON(url,JSON.stringify(MarksEntry), function (data) {
            Success = data;
       });
      //  return Success
       // alert(marksEntrylist);
        //Index = $(this).index()   1;
       // MarksEntry.ExamDate = Formateddate;
       // result = result   CreateMarksEntry(this);
     });
     if (result > 0) {
        $("#Complete").html("No.of Records saved:"   result);
        $("#Complete").dialog({
            resizable: false,
            height: 140,
            modal: true,
            autoOpen: true,
            buttons: {
                'Done': function () {
                    $(this).dialog('close');
                    var url = $("#RedirectTo").val();
                    location.href = url;
                }
            }
        });


    }
    else {

        alert('Records havent been saved');
    }


     function CreateMarksEntry(objTr) {
         var cols = $(objTr).find('td');
         // this.Name = $(cols[0]).html();
         if ($(cols[4]).html() == "amp;nbsp;") {
             this.MarksEntered = "";
         }
         if ($(cols[5]).html() == "amp;nbsp;") {
             this.RemarksEntered = "";
         }
         var Details={
             //this.RollNo = $(cols[1]).html();
             //this.AdmissionNo = $(cols[2]).html();

             MarksEntered: $(cols[4]).html(),
             remarksentered: $(cols[5]).html()
             }
        // this.RemarksEntered = $(cols[5]).html();
       //  if (this.Name == "amp;nbsp;") {
        //     this.Name = "";
       // }
       //  if (this.RollNo == "amp;nbsp;") {
       //      this.RollNo = "";
       // }
        // if (this.AdmissionNo == "amp;nbsp;") {
        ///     this.AdmissionNo = "";
       // }
         if (this.MarksEntered == "amp;nbsp;") {
             this.MarksEntered = "";
       }
        if (this.RemarksEntered == "amp;nbsp;") {
            this.RemarksEntered = "";
      }
     //   $.getJSON(url, MarksEntry, function (data) {
       //     Success = data;
       // });
       // return Success
    };


}


    model

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace Examination.Domain.ViewModel
    {
        public class vmStudentMarks
        {
            public string ExamTypeDesc { get; set; }
            public int Subjectid { get; set; }
            public int ClassSectionID { get; set; }
            public string ExamDate { get; set; }
            public int ExaminationID { get; set; }
            public int Id { get; set; }
            public string SchoolId { get; set; }
            public string SessionId { get; set; }
            public string Name { get; set; }
            public string AdmissionNo { get; set; }
            public string RollNo { get; set; }
            public string Written { get; set; }
            public string Oral { get; set; }
            public string Practical { get; set; }
            public string PASS_FAIL { get; set; }
            public string Project { get; set; }
            public string RemarksEntered { get; set; }
            public string MarksEntered { get; set; }
            public string ClassSection { get; set; }
            public string SubjectName { get; set; }
            public string StudentId { get; set; }
            public long EXAM_RESULT_ID{ get; set; }
            public long EXAM_RESULT_DET_ID { get; set; }
            public int MAX_MARKS { get; set; }
            public bool Present { get; set; }
            public int ENTRY_USER_ID { get; set; }
            public int UPDATE_USER_ID { get; set; }
            public int GRACE { get; set; }


    //public MarksEntryDetails[] @List { get; set; }
            public List<MarksEntryDetails> MarksEntryDetails { get; set; }

        }
        public class MarksEntryDetails
        {
            public string StudentId { get; set; }
            public string MarksEntered { get; set; }
            public string remarksentered { get; set; }
            public int total_oral_marks { get; set; }
            public int total_practical_marks { get; set; }
            public int total_project_marks { get; set; }
            public int total_marks { get; set; }
            public int present { get; set; }
            public string pass_fail { get; set; }
            public int grace { get; set; }
        }
    }
    controller

       [AcceptVerbs(HttpVerbs.Get)]
            public ActionResult CreateRecords(vmStudentMarks MarksEntry)
            {
                MarksEntry.MarksEntryDetails[0].MarksEntered.ToString();//error throws as object not intialised
                UserProfile userProfile = SchoolSession.CurrentUser;
                int Sucess = examScoreService.PostMARKSENTRYDETAILS(userProfile.School.Id, userProfile.CurrentSession.Id, 

    userProfile.EmployeeId,MarksEntry);
                return Json(Sucess, JsonRequestBehavior.AllowGet);

            }
  

Ответ №1:

Вы можете использовать JSON.stringify при публикации данных для передачи множества объектов контроллеру.

 $.ajax(
{
    url: 'controller/CreateRecords',
    data: JSON.stringify({MarksEntry: MarksEntry}),
    contentType: 'application/json',
    dataType: 'json',
    type: 'POST',
    success: function (data) {
        // success
    },
    error: function () {
       // error
    }
});
  

Пожалуйста, обратитесь к следующему сообщению для получения дополнительной информации.

Передача сложного объекта JavaScript в контроллер MVC

Это иллюстрирует, как мы можем передавать сложные объекты javascript в контроллер MVC.

Спасибо!

Комментарии:

1. Пожалуйста, скопируйте информацию из ссылок здесь вместо этого, ответы только по ссылкам считаются «ненастоящими» ответами и могут быть удалены

2. Это не помогает, любезно, поскольку в контроллере я получаю массив с объектом и значением null