We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

Populate Grid Cell with a value in a list object in the Data Sourse

I have a class object containing List objects as shown below:

public class StudentTestScores : BaseModel
{
public string StudNo { getset; }
public string School { getset; }
public string FirstName { getset; }
public string LastName { getset; }
public List<ScoreInfo> ScaleScores { getset; }
public List<ScoreInfo> Levels { getset; }
public List<ScoreInfo> RawScores { getset; }
public List<ScoreInfo> Quartile { getset; }
public List<ScoreInfo> PercentileRank { getset; }
public List<ScoreInfo> PercentileiReady { getset; }
public List<ScoreInfo> SubSkill1 { getset; }
public List<ScoreInfo> SubSkill2 { getset; }
public List<ScoreInfo> SubSkill3 { getset; }
public List<ScoreInfo> SubSkill4 { getset; }
public List<ScoreInfo> SubSkill5 { getset; }
public List<ScoreInfo> Vocabulary { getset; }
public List<ScoreInfo> Phonics { getset; }
public List<ScoreInfo> High_Frequency { getset; }
public List<ScoreInfo> Literature { getset; }
public List<ScoreInfo> Informational { getset; }
public List<ScoreInfo> Correct { getset; }
public List<ScoreInfo> MCCorrect { getset; }
public List<ScoreInfo> TEICorrect { getset; }
public List<ScoreInfo> NPR { getset; }
public List<ScoreInfo> Score { getset; }
public int SchoolYear { getset; }
public List<string> Subjects { getset; }
}

and:
public class ScoreInfo
{
    public string SubjectName { getset; }
    public int Score { getset; }
    public string Schoolyear { getset; }
    public string AdministrationName { getset; }
    
}
the Grid is being build as:
@{
    ViewBag.Title = "SyncFusionListView";
    Layout = "~/Views/Shared/_Layout.cshtml";
    IEnumerable<StudentTestScores> dataSource = (IEnumerable<StudentTestScores>)Model;
}
@section SampleHeading{<span class="sampleName"> </span>}
@section ControlsSection{
    @(Html.EJ().Grid<StudentTestScores>("FlatGrid")
                                .Datasource(dataSource)
                .ToolbarSettings(toolBar => toolBar.ShowToolbar().ToolbarItems(items =>
            {
                items.AddTool(ToolBarItems.ExcelExport);
                items.AddTool(ToolBarItems.WordExport);
                items.AddTool(ToolBarItems.PdfExport);
                items.AddTool(ToolBarItems.PrintGrid);
            }))
        .AllowSorting()
        .AllowPaging()
        .PageSettings(page => { page.PageSize(5); })
        .Columns(col =>
        {
            StudentTestScores studentTestScore = dataSource.First();
            Type modelType = studentTestScore.GetType();
            IList<PropertyInfo> props = new List<PropertyInfo>(modelType.GetProperties());
           
            foreach (PropertyInfo prop in props)
            { 
                string propName = prop.Name;
                var val = prop.GetValue(studentTestScore, null);
                if (val != null)
                {
                    string header = propName;
                    string myType = val.GetType().Name.ToString();
                    if (myType.ToLower().Contains("list")) // this is ScoreInfo
                    {
                        var scoreInfoLst = (List<ScoreInfo>)val;
                        if (scoreInfoLst.Count > 0)
                        {
                            ScoreInfo scoreInfo = scoreInfoLst[0];
                            header = String.Format("{0} {1} {2}", scoreInfo.SubjectName, scoreInfo.AdministrationName, propName);
                            col.Field(prop.Name).HeaderText(header).TextAlign(TextAlign.Center).Add();
 
                        }
                    }
                    else
                    {
                        if (header == "FirstName") col.Field("FirstName").HeaderText("First Name").TextAlign(TextAlign.Left).Add();
                        if (header == "LastName") col.Field("LastName").HeaderText("Last Name").TextAlign(TextAlign.Left).Add();
 
                    }
                }
            }
        }))
 
}
 
@Html.EJ().ScriptManager()
I need to set ScoreInfo.Score need as the value for the respective column but. Can anyone give me some help on this?

4 Replies

JK Jayaprakash Kamaraj Syncfusion Team May 27, 2016 12:50 PM UTC

Hi Lucio, 

Thanks for contacting Syncfusion support. 

If column property type is  collection of array we need to traverse data with dot and index. So, we suggest you to use the below code example, to bind ScoreInfo.Score value for the respective column in Grid .  
 
if (val != null) 
                { 
                    string header = propName; 
                    string myType = val.GetType().Name.ToString(); 
                    if (myType.ToLower().Contains("list")) // this is ScoreInfo 
                    { 
                        var scoreInfoLst = (List<SyncfusionMvcApplication84.Controllers.GridController.ScoreInfo>)val; 
                        if (scoreInfoLst.Count > 0) 
                        { 
                            SyncfusionMvcApplication84.Controllers.GridController.ScoreInfo scoreInfo = scoreInfoLst[0]; 
                            header = String.Format("{0} {1} {2}", scoreInfo.Score, scoreInfo.AdministrationName, propName); 
                            string Score = string.Concat(propName, ".0.","Score"); 
                            col.Field(Score).HeaderText(header).TextAlign(TextAlign.Center).Add(); 
 
                        } 
                    } 


Regards, 
Jayaprakash K. 



LA Lucio A. Da Silva May 27, 2016 03:55 PM UTC

Thank you for your response.
I have implemented another method to retrieve:
StudentTestScores studentTestScore = students.First();
Type modelType = studentTestScore.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(modelType.GetProperties());
 
IList<object> dataSource = new List<object>();
IList<string> headers = new List<string>();
 
foreach (StudentTestScores sts in students)
{
    Dictionary<stringstring> dic = new Dictionary<stringstring>();
    foreach (PropertyInfo prop in props)
    {
        string propName = prop.Name;
        var val = prop.GetValue(sts, null);
        if (val != null && propName != "StudNo" && propName != "SchoolYear" && propName != "Data")
        {
            string header = propName;
            string myType = val.GetType().Name.ToString();
            if (myType.ToLower().Contains("list")) // this is ScoreInfo
            {
                var scoreInfoLst = (List<ScoreInfo>)val;
                if (scoreInfoLst.Count > 0)
                {
                    ScoreInfo scoreInfo = scoreInfoLst[0];
                    header = String.Format("{0} {1} {2}", scoreInfo.SubjectName, scoreInfo.AdministrationName, propName);
                    dic.Add(header, scoreInfo.Score.ToString());
                    if (!headers.Contains(header))
                    {
                        headers.Add(header);
                    }
                    
                }
            }
            else
            {
                if (header == "FirstName") header = "First Name"//col.Field("FirstName").HeaderText("First Name").TextAlign(TextAlign.Left).Add();
                if (header == "LastName") header = "Last Name"//col.Field("LastName").HeaderText("Last Name").TextAlign(TextAlign.Left).Add();
                dic.Add(header, val.ToString());
                if (!headers.Contains(header))
                {
                    headers.Add(header);
                }
                    
            }
        }
    }
    
    dataSource.Add((object)dic);
}
 
List<Column> cols = new List<Column>();
foreach (string h in headers)
{
    cols.Add(new Column() { Field = h, HeaderText = h });
}
ViewBag.columns = cols;
 
return (IEnumerable<object>)dataSource;
And Razor:
@(Html.EJ().Grid<StudentTestScores>("gvStudentsScores")
        .Datasource(dataSource)
        .ToolbarSettings(toolBar => toolBar.ShowToolbar().ToolbarItems(items =>
        {
            items.AddTool(ToolBarItems.ExcelExport);
            items.AddTool(ToolBarItems.WordExport);
            items.AddTool(ToolBarItems.PdfExport);
            items.AddTool(ToolBarItems.PrintGrid);
        }))
        .AllowSorting()
        .AllowPaging()
        .PageSettings(page => { page.PageSize(20); })
                .Columns(cols)
)
 
@Html.EJ().ScriptManager()

Now I am facing another problem:
According to what user selects, other columns are to be added on postback but the Grid columns are not being updated to match the new columns set.




LA Lucio A. Da Silva replied to Lucio A. Da Silva May 27, 2016 03:58 PM UTC

Thank you for your response.
I have implemented another method to retrieve:
StudentTestScores studentTestScore = students.First();
Type modelType = studentTestScore.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(modelType.GetProperties());
 
IList<object> dataSource = new List<object>();
IList<string> headers = new List<string>();
 
foreach (StudentTestScores sts in students)
{
    Dictionary<stringstring> dic = new Dictionary<stringstring>();
    foreach (PropertyInfo prop in props)
    {
        string propName = prop.Name;
        var val = prop.GetValue(sts, null);
        if (val != null && propName != "StudNo" && propName != "SchoolYear" && propName != "Data")
        {
            string header = propName;
            string myType = val.GetType().Name.ToString();
            if (myType.ToLower().Contains("list")) // this is ScoreInfo
            {
                var scoreInfoLst = (List<ScoreInfo>)val;
                if (scoreInfoLst.Count > 0)
                {
                    ScoreInfo scoreInfo = scoreInfoLst[0];
                    header = String.Format("{0} {1} {2}", scoreInfo.SubjectName, scoreInfo.AdministrationName, propName);
                    dic.Add(header, scoreInfo.Score.ToString());
                    if (!headers.Contains(header))
                    {
                        headers.Add(header);
                    }
                    
                }
            }
            else
            {
                if (header == "FirstName") header = "First Name"//col.Field("FirstName").HeaderText("First Name").TextAlign(TextAlign.Left).Add();
                if (header == "LastName") header = "Last Name"//col.Field("LastName").HeaderText("Last Name").TextAlign(TextAlign.Left).Add();
                dic.Add(header, val.ToString());
                if (!headers.Contains(header))
                {
                    headers.Add(header);
                }
                    
            }
        }
    }
    
    dataSource.Add((object)dic);
}
 
List<Column> cols = new List<Column>();
foreach (string h in headers)
{
    cols.Add(new Column() { Field = h, HeaderText = h });
}
ViewBag.columns = cols;
 
return (IEnumerable<object>)dataSource;
And Razor:
@(Html.EJ().Grid<StudentTestScores>("gvStudentsScores")
        .Datasource(dataSource)
        .ToolbarSettings(toolBar => toolBar.ShowToolbar().ToolbarItems(items =>
        {
            items.AddTool(ToolBarItems.ExcelExport);
            items.AddTool(ToolBarItems.WordExport);
            items.AddTool(ToolBarItems.PdfExport);
            items.AddTool(ToolBarItems.PrintGrid);
        }))
        .AllowSorting()
        .AllowPaging()
        .PageSettings(page => { page.PageSize(20); })
                .Columns(cols)
)
 
@Html.EJ().ScriptManager()

Now I am facing another problem:
According to what user selects, other columns are to be added on postback but the Grid columns are not being updated to match the new columns set.



missed this info:
@{
    ViewBag.Title = "Grid";
    Layout = null;
    IEnumerable<object> dataSource = (IEnumerable<object>)Model;
    List<Column> cols = (List<Column>)ViewBag.columns;
}


JK Jayaprakash Kamaraj Syncfusion Team May 30, 2016 12:03 PM UTC

Hi Lucio, 
 
We have initially rendered grid with 20 columns, then in button click we have rendered grid with 4 columns using columns method. This method is used to add or remove columns in grid column collections. Please refer to the below Help document, code example and sample.   
 

GridFeatures.cshtml 
<button id="click">Refresh Column</button> 
@(Html.EJ().Grid<SyncfusionMvcApplication84.Controllers.GridController.Orders>("FlatGrid") 
        .Datasource(dataSource) 
         .AllowPaging()    /*Paging Enabled*/ 
            .Columns(ViewBag.columns)) 
<script type="text/javascript"> 
    $("#click").click(function () { 
 
        $.ajax({ 
            url: "/Grid/NewColumn", 
            type: "POST", 
            datatype: "json", 
            contentType: "application/json", 
 
            success: function (result) { 
                var columns =  JSON.parse(result); // deserialize the columns 
                var obj = $("#FlatGrid").ejGrid("instance") 
                obj.model.columns=[]; //if you want add to additonal columns please remove this line 
                obj.columns(columns); // refresh the grid columns 
            } 
        }); 
 
    }); 
 
 
</script>GridController.cs 
        public ActionResult NewColumn() 
        { 
            SerializeObject serialize = new SerializeObject(); 
              string newcol = serialize.SerializeToJson(cols.Take(4).ToList());// serialize the new coluumns columns 
             return Json(newcol); 
        } 


If we have misunderstood your requirement, please share the following:   
1.       Do you want to add/remove columns in grid?   
2.       In which scenario you want to update columns?   
3.       Clearly explain your requirement   
 
Regards, 
Jayaprakash K. 
 


Loader.
Live Chat Icon For mobile
Up arrow icon