Multiple Substring is not working in MVC Razor view RRS feed

  • Question

  • User-471420332 posted

    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++)
                                  //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))
                                        <a href='/PatientManagement/DownloadUploadedDocument?fileName=@Html.Raw(i.path)'>Download</a>

    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)
    Monday, May 24, 2021 9:51 PM

All replies

  • User303363814 posted

    Substring(4,5) means ... starting at the fifth character (the first parameter is zero based) take the next five characters.  That is, take characters 5, 6, 7, 8 and 9

    Your string only has eight characters.  You cannot take the ninth because it does not exist.

    'Index and length must refer to a location within the string' - how could this message be more explicit?

    Monday, May 24, 2021 10:39 PM
  • User409696431 posted

    Substring(Int32, Int32)

    The first int is the zero-based index to start at. That means the first character is index 0.

    The second int is the length (number of characters) in the Substring.

    Your first example asks for starting at index zero (the first character), and returning 5 characters.  It will work, returning "20210".

    Your second example will not work.  The starting index is 4 (zero-based), so it is starting with the second zero, that is, it is working with "0225", and you are asking it for 5 characters.  Only four are left.  As the error says, the length is wrong.

    I suspect you are misunderstanding the zero-based index.  If you want the last five characters, you would use:

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

    Monday, May 24, 2021 10:48 PM