Home > Enterprise >  Converting string to int for comparison
Converting string to int for comparison

Time:10-25

I have identity set up on my Razor pages ASP.NET Core web application, and I've set the user name to V003950. A bit of backstory on my web app is that you can upload/download files, an admin can upload and assign a user, then the user logs on and can only see their files.

The id I am trying to compare it to is an integer, and the Id is 3950, so I'm trying to do an if statement like this:

@foreach (var item in Model.Files)
    {
        if(User.Identity?.Name! == item.VendorId){
            if (item.FileType == "Purchase Order")
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Number)
                    </td>
                    @*<td>
                        @Html.DisplayFor(modelItem => item.Date)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Value)
                    </td>*@
                    @*<td>
                        @Html.DisplayFor(modelItem => item.FileType)
                    </td>
                    <td>
                        <a asp-page="Upload" asp-route-id="@item.Id">Upload File</a>
                    </td>*@
                    <td>
                        @if (item.Attachment != null)
                        {
                            <form asp-page-handler="Download" method="post" asp-route-id="@item.Id">
                                <input type="submit"  value="Download">
                            </form>
                        }
                    </td>
                </tr>
            }
        }
    }

but because one is a string and one is an int it doesnt work. I've also tried converting the name to int, but the V at the start is becoming a problem.

Is there a way for me to remove the leading V from the if or maybe add in a .contains instead?

CodePudding user response:

Combining the ideas mentioned in the comments, I suggest to remove the first character from Name using String.Substring, then convert it to int using int.TryParse and finally compare it to the VendorId, like this:

if (int.TryParse(User.Identity?.Name?.Substring(1), out int nameAsInteger) &&
    nameAsInteger == item.VendorId)
{
}

CodePudding user response:

If your UserName are all in the style of V some number, So you can use this code:

@foreach (var item in Model.Files)
    {
       var result = User.Identity?.Name;
       if(result!=null){
           if(Int32.Parse(result.Substring(1, result.Length - 1)) == item.VendorId){
              //.......
              }
       }
   }

CodePudding user response:

Try converting your integer to string with .ToString()

Like rbdeenk mentioned in his comment you can get rid of the "V" in your name using

.Trim( new Char[] { 'v', 'V' } )

and then compare the two strings.

  • Related