将数组中的JSON列表绑定到ASP.NET模型类

时间:2014-03-17 23:42:18

标签: javascript jquery asp.net-mvc json

我正在从我的数组构建JSON输出,我打算将其传递回服务器,在那里我有模型类将JSON数据变量绑定到类变量。在这个课程中,我也会为参数'Component'提供多个say的记录,并且绑定这个部分我在我的模型类中有IList。

现在我已经设法将数据传回控制器,除了IList中的组件......我很难找到答案..你的帮助将非常感激..

模型类

 public class QualificationElementComponents_ViewModel
{

    public int ElementIndex { get; set; }
    public string ElementMarkingSchemeTitle { get; set; }
    public int ElementAvailableMark { get; set; }
    public int ElementPassMark { get; set; }
    public int ElementMeritMark { get; set; }
    public int ElementDistinctionMark { get; set; }

    public IList<ECom1> ElementComponent { get; set; }

}

IList'Component'模型类

 public class ECom1
{
    public int componentIndex { get; set; }
    public int componentMark { get; set; }
}

控制器方法

  public ActionResult CreateNewQualification(QualificationViewModel newQualificationData, IList<QualificationElementComponents_ViewModel> ElementComponentList)
   {

在视图中

//build component list... possible will have multiple records in array
selectedComponentList.push({ componentIndex: recordId, componentMark: ComponentSchemeMark });

// build element list
selectElementList.push({ ElementIndex: E_RecordId, ElementMarkingSchemeTitle: E_MarkingSchemeTitle, ElementAvailableMark: E_AvailableMark, ElementPassMark: E_PassMark, ElementMeritMark: E_MeritMark, ElementDistinctionMark: E_DistinctionMark });

 //bind arrays 

 selectElementList.push({ ElementComponent: selectedComponentList });

        QualificationElemenetsAndComponentsList.push.apply(QualificationElemenetsAndComponentsList, selectElementList);

JSON输出

{"QualificationElemenetsAndComponentsList":[{"ElementIndex":1,"ElementMarkingSchemeTitle":"fg","ElementAvailableMark":"56","ElementPassMark":"6","ElementMeritMark":"5","ElementDistinctionMark":"6"},{"ElementComponent":[{"componentIndex":1,"componentMark":"23"},{"componentIndex":2,"componentMark":"44"}]}]}

需要JSON输出

与上述JSON相比,我需要遵循JSON格式

{"QualificationElemenetsAndComponentsList":[{"ElementIndex":1,"ElementMarkingSchemeTitle":"d2","ElementAvailableMark":"223","ElementPassMark":"32","ElementMeritMark":"12","ElementDistinctionMark":"2","ElementComponent":[{"componentIndex":2,"componentMark":551}]}]}

1 个答案:

答案 0 :(得分:1)

不是将ElementComponent属性添加到新对象然后再添加到数组中,而是需要将其包含在其他属性中,如下所示:

    //build component list... possible will have multiple records in array
    selectedComponentList.push({ componentIndex: recordId, componentMark: ComponentSchemeMark });

    // build element list
    selectElementList.push({ ElementIndex: E_RecordId, ElementMarkingSchemeTitle: E_MarkingSchemeTitle, ElementAvailableMark: E_AvailableMark, ElementPassMark: E_PassMark, ElementMeritMark: E_MeritMark, ElementDistinctionMark: E_DistinctionMark, ElementComponent: selectedComponentList });
    //Add ElementComponent with all the other properties