Search code examples
jqueryasp.net-mvc-5razor-2

asp.net mvc5 : how to make Model Id hidden so that no one can change from browser using inspect element


I have a model named 'User' having fields 'UserId, Username, Status', In index page i am enlisting all users along with edit , delete functionality. Here is my code

@foreach (var item in Model)
{
   <table>
     <tr>
       <td>@Html.DisplayFor(modelItem => item.Username)</td>
       <td>@Html.DisplayFor(modelItem => item.Status)</td>
       <td><input type='button' id='btnEdit' data-id='@item.UserId' value='Edit'/></td>
     </tr>
   </table>
}

It is rendered as

   <table>
     <tr>
       <td>USER ONE</td>
       <td>active</td>
       <td><input type='button' id='btnEdit' data-id='1041' value='Edit'/></td>
     </tr>
     <tr>
       <td>USER TWO</td>
       <td>active</td>
       <td><input type='button' id='btnEdit' data-id='1042' value='Edit'/></td>
     </tr>
   </table>

And upon clicking btnEdit, i user jQuery ajax call to controller like this:

$("#btnEdit").on("click", function () {
    $.ajax({
        cache: false,
        type: "POST",
        url: "/User/Edit",
        data: $(this).data('id'),
        success: function (response) {
            //rest of code here
        }
    });
});

QUESTION:

How to make UserId hidden and call it from jquery against selected row, so that no one can change from browser using inspect element


Solution

  • For future readers, I wanted to mark this question as solved, thanks Stephen Muecke, Vinay Singh, Zoran for their valuable time and guidance.

    Here are the steps what i did to make my site less vulnerable.

    1. Used form with Antiforgerytoken to disrespect any such malicious requests. (as suggested by Vinay Singh)

    2. Encrypted / Decrypted my ids so that atleast normal end user cannot play with them by changing their value. (as suggested by Zoran)

    3. Most importantly to prevent from bad end user, i am validating each request at server side, whether or not current user is authorized to make this request etc. (as suggested by Sir Stephen Muecke)