Search code examples
c#asp.netasp.net-mvcrazor

Multiple Substring is not working in MVC Razor view


In razor view below For Each using

 @foreach (var i in (List<MyDME.Data.Model.ERNFileRequestDTO>)ViewBag.lst)
                    {
                        for (int j = 0; j < i.Parse835Details.storedChkNo.Count; j++)
                        {

                            <tr>
                                <td>
                                    @i.Parse835Details.storedPayorName[j]
                                </td>
                                <td>
                                    @i.Parse835Details.storedChkNo[j]
                                </td>
                                <td>
                                    @i.Parse835Details.storedTotalBilled[j]

                                </td>
                                <td>
                                    @i.Parse835Details.storedTotalPaid[j]

                                </td>
                                <td>
                              //below line doing substring which is not working
   @(i.Parse835Details.storedChkDate[j].Substring(4, 5) + " " + i.Parse835Details.storedChkDate[j].Substring(6, 7) + " " + i.Parse835Details.storedChkDate[j].Substring(0, 3))
                                   
                                </td>
                                <td>
                                    <a href='/PatientManagement/[email protected](i.path)'>Download</a>

                                </td>
                            </tr>

below error is getting

System.ArgumentOutOfRangeException: 'Index and length must refer to a location within the string. Parameter name: length'

IF i.Parse835Details.storedChkDate[j] vlaues is 20210225 like that date format is coming in string, from this value doing substring but not able to do substring for multiple substring.

if i use below single range then its working

@i.Parse835Details.storedChkDate[j].Substring(0, 5)

if i use below single range then its not working

@i.Parse835Details.storedChkDate[j].Substring(4, 5)

Solution

  • You are using the method public string Substring (int startIndex, int length).
    But it seems you think it is public string Substring (int startIndex, int endIndex).

    The extract characters 4 + 5, you need to pass length as 2, as follows:

    @i.Parse835Details.storedChkDate[j].Substring(4, 2)
    

    And similar for the other calls.