locked
How can I loop through Model List used in Html table, from in JavaScript RRS feed

  • Question

  • User-1355965324 posted

    I have the following HTML and I want to loop through  Model List from JavaScript . Is that possible to find the value of one item from Model List obejct from Javascript, Please can you help me

    @Model Attendance
     <table id="empTable" >
        <tr>
            <th>
                Employee Name
            </th>
            <th>
                Designation
            </th>
         <th>
                Status
            </th>
            
        </tr>
    for (i = 0; i < Model.attendanceLogList.Count; i++)
    {
        <tr>
                   <td>@Model.attendanceLogList[i].EmployeeName</td>
                   <td>@Model.attendanceLogList[i].Designation</td>
               <td>@Model.attendanceLogList[i].IsProtected</td>  // it is boolean in model
           
          </tr>
    }
    
    
    </table>
    <script>
            for (var i = 0; i < @Model.attendanceLogList.length; i++) {
    	var item = @Model.attendanceLogList.IsProtected(i)
    console.log(item); } </script>

    With Thanks

    Pol

    Wednesday, November 11, 2020 3:36 PM

Answers

  • User711641945 posted

    Hi polachan,

    Not sure what you want to do by looping the value in js,here is a working demo about how to loop in js:

    @section Scripts
    {
        <script>
            var item = true;
            @for (var i = 0; i < Model.attendanceLogList.Count; i++) {
                 @: item = `@Model.attendanceLogList[i].IsProtected`;
                 @: console.log(item);
            }
        </script>
    }

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 12, 2020 2:11 AM
  • User711641945 posted

    Hi polachan,

    Firstly,when the page comes,Model.AttendanceLogList will be null. You can't make it null,otherwise, the js would make error.

    You need to initialize the data like below:

    public IActionResult Index()
    {
        var model = new Log() {
            attendanceLogList = new List<AttendanceLog>()  //initialize it
        };
        return View(model);
    }

    Here is a simple demo:

    Model:

    public class Log
    {
        public int Id { get; set; }
        public List<AttendanceLog> attendanceLogList { get; set; }
    }
    public class AttendanceLog
    {
        public string EmployeeName { get; set; }
        public string ExtraTimeHrs { get; set; }
        public string Remark { get; set; }
        public bool IsProtected { get; set; }
    }

    View:

    @model Log
    <form asp-action="GetEmployee">
        <select onchange="this.form.submit()" asp-for="Id">
            <option value="0">User1</option>
            <option value="1">User2</option>
        </select>
    </form>
    
     
    <table id="empTable">
        <tr>
            <th>
                Employee Name
            </th>
            <th>
                Designation
            </th>
            <th>
                Status
            </th>
    
        </tr>
        @if (Model.attendanceLogList.Count != 0)
        {
            @for (var i = 0; i < Model.attendanceLogList.Count; i++)
            {
                <tr>
                    <td>@Model.attendanceLogList[i].EmployeeName</td>
                    <td>@Model.attendanceLogList[i].IsProtected</td>
    
                </tr>
            }
    
        }
    </table>
    
    
    @section Scripts
    {
        <script>
            var count = '@Model.attendanceLogList.Count';
            if (count != '') {
                var item = true;
                @for (var i = 0; i < Model.attendanceLogList.Count; i++) {
                        @: item = `@Model.attendanceLogList[i].IsProtected`;
                        @: console.log(item);
                }
            }        
        </script>
    }
    
    

    Controller:

    public IActionResult Index()
    {
        var model = new Log() {
            attendanceLogList = new List<AttendanceLog>()
        };
        return View(model);
    }
    public IActionResult GetEmployee(int id)
    {
        var model = new List<Log>()
        {                
            //...
        };
        var data = model.Where(a => a.Id == id).FirstOrDefault();
        return View("Index",data);
    }

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 13, 2020 8:55 AM
  • User711641945 posted

    Hi polachan,

    My code works well although no rows in table,could you please share your razor view?Be sure to add the if statement to judge the record exsits or not.Something like:

    @if (Model.attendanceLogList.Count != 0) or  @if (Model.attendanceLogList==null)

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 18, 2020 5:07 AM

All replies

  • User-474980206 posted

    Not the way you are. The razor code is executed at render so

     @Model.attendanceLogList.length

    renders the length as a string in the html. But 

     @Model.attendanceLogList.IsProtected(i)

    The i is a c#  variable, which is undefined. The model unless you render it as json, is not a viable to JavaScript. You can loop thru the table html and get the values. See jquery documentation.

    Wednesday, November 11, 2020 4:07 PM
  • User-1355965324 posted

    Thanks Bruce, I know  loop through html table .But the problem is in some condition , the column position  would be re-ordered , some times  column  would be kept as hidden  depends some other data.  So I cannot give the column number . if I can loop through model  to get the value it will work.

    Pol

    Wednesday, November 11, 2020 4:50 PM
  • User-474980206 posted

    then you need to render the model as a javascript variable. as this exposes the whole model to the user, use with caution.

        var model = @(JsonSerializer.Serialize(Model));

    a better approach is to only render what is needed from the model.

    Wednesday, November 11, 2020 9:57 PM
  • User711641945 posted

    Hi polachan,

    Not sure what you want to do by looping the value in js,here is a working demo about how to loop in js:

    @section Scripts
    {
        <script>
            var item = true;
            @for (var i = 0; i < Model.attendanceLogList.Count; i++) {
                 @: item = `@Model.attendanceLogList[i].IsProtected`;
                 @: console.log(item);
            }
        </script>
    }

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 12, 2020 2:11 AM
  • User-1355965324 posted

    Thanks Rena

    First time  the page is coming , Model.AttendanceLogList will be null. There is no record initially . Afterwards I have to pick a date from the dropdown , then  corresponding records would be filled  in the model.AttendanceLogList. How can I check the empty list .At the moment there is an error  is coming  when the first time page is being showed because of Model.attendanceLogList is empty.

    Please can you help  for that problem too

    Many thanks

    Thursday, November 12, 2020 3:52 PM
  • User-474980206 posted

    you can use if statement to test for null, or in the controller, set model to an empty list rather than null.

    Thursday, November 12, 2020 4:23 PM
  • User711641945 posted

    Hi polachan,

    Firstly,when the page comes,Model.AttendanceLogList will be null. You can't make it null,otherwise, the js would make error.

    You need to initialize the data like below:

    public IActionResult Index()
    {
        var model = new Log() {
            attendanceLogList = new List<AttendanceLog>()  //initialize it
        };
        return View(model);
    }

    Here is a simple demo:

    Model:

    public class Log
    {
        public int Id { get; set; }
        public List<AttendanceLog> attendanceLogList { get; set; }
    }
    public class AttendanceLog
    {
        public string EmployeeName { get; set; }
        public string ExtraTimeHrs { get; set; }
        public string Remark { get; set; }
        public bool IsProtected { get; set; }
    }

    View:

    @model Log
    <form asp-action="GetEmployee">
        <select onchange="this.form.submit()" asp-for="Id">
            <option value="0">User1</option>
            <option value="1">User2</option>
        </select>
    </form>
    
     
    <table id="empTable">
        <tr>
            <th>
                Employee Name
            </th>
            <th>
                Designation
            </th>
            <th>
                Status
            </th>
    
        </tr>
        @if (Model.attendanceLogList.Count != 0)
        {
            @for (var i = 0; i < Model.attendanceLogList.Count; i++)
            {
                <tr>
                    <td>@Model.attendanceLogList[i].EmployeeName</td>
                    <td>@Model.attendanceLogList[i].IsProtected</td>
    
                </tr>
            }
    
        }
    </table>
    
    
    @section Scripts
    {
        <script>
            var count = '@Model.attendanceLogList.Count';
            if (count != '') {
                var item = true;
                @for (var i = 0; i < Model.attendanceLogList.Count; i++) {
                        @: item = `@Model.attendanceLogList[i].IsProtected`;
                        @: console.log(item);
                }
            }        
        </script>
    }
    
    

    Controller:

    public IActionResult Index()
    {
        var model = new Log() {
            attendanceLogList = new List<AttendanceLog>()
        };
        return View(model);
    }
    public IActionResult GetEmployee(int id)
    {
        var model = new List<Log>()
        {                
            //...
        };
        var data = model.Where(a => a.Id == id).FirstOrDefault();
        return View("Index",data);
    }

    Result:

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 13, 2020 8:55 AM
  • User-1355965324 posted

    Rena

    When I apply your code and if there is no rows in table, the following error message would be displayed. It will work only if record exist in table

    NullReferenceException: Object reference not set to an instance of an object.
    AspNetCore._Views_Employee_EmployeeAttendance_cshtml+<ExecuteAsync>d__52.MoveNext() in EmployeeAttendance.cshtml,  

    Monday, November 16, 2020 10:43 AM
  • User711641945 posted

    Hi polachan,

    My code works well although no rows in table,could you please share your razor view?Be sure to add the if statement to judge the record exsits or not.Something like:

    @if (Model.attendanceLogList.Count != 0) or  @if (Model.attendanceLogList==null)

    Best Regards,

    Rena

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 18, 2020 5:07 AM