Notification triggered in GridView editing according to authorization levels

I have a formview displaying data with an option to edit each row. There are different user roles in my system such as Admin, SuperUser, and User. If a non-Admin user tries to edit a row, I want to display a warning message. Currently, the JavaScript function I implemented shows the alert for all users because there is no validation in place.

ATTEMPT SO FAR

FormView:

<ItemTemplate>
    <asp:ImageButton ID="btnEdit" OnClientClick="myFunction()" runat="server" CommandName="Edit" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ImageUrl="~/Images/Edit.gif" />
</ItemTemplate>

Javascript:

function myFunction() {
        var edit;
        if (confirm("For ADMIN only. Do not edit/delete the row. Still want to continue?") == true) {
        }
        else {
            window.location.reload();
        }
        document.getElementById("btnEdit").innerHTML = edit;
    }     

Identifying current user:

The current logged-in user's information is displayed on the page using the following code snippet. The username is stored in a label.

protected void Page_Load(object sender, EventArgs e)
{
    checkUser();
}

public void checkUser()
{
    string currentUser = HttpContext.Current.Request.LogonUserIdentity.Name;
    string[] words = currentUser.Split('\\');
    currentUser = words[1];
    DataSet ds = new DataSet();
    using (SqlConnection conn = new SqlConnection(strcon))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        string strQuery = "select UserId from Permissions where UserId='" +  currentUser + "'";
        SqlCommand cmd = new SqlCommand(strQuery, conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
    }
    lblUser.Text = ds.Tables[0].Rows[0]["UserName"].ToString();
}

Within the Permissions table, I have a column called 'Roles' which I need to use to verify if the user is not an Admin and provide an alert accordingly. Any guidance or assistance on achieving this would be greatly appreciated.

Answer №1

give this approach a try

execute the following script

     <script language="javascript" type="text/javascript>
      function validateUser() {
          var confirmEdit = confirm("Are you sure you want to proceed?");
          if (confirmEdit) {
              return true;
          }
          else {
              return false;
          }
       } 
      </script>

Invoke the function using OnClick="return validateUser();"

Answer №2

To accomplish this task, follow these steps:

protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
  {
    Button editButton = e.Row.FindControl("editBtn") as Button;
    if(lblUser.Text !="Admin")
      editButton.OnClientClick = "alert('Access denied');return false;";
  }
}

If you wish to utilize your own function, modify the code snippet like so:

 editButton.OnClientClick = "return customFunction()";

Answer №3

Have you considered implementing this on the server side? By checking permissions within the Edit function, you can prevent 'smart' users from bypassing your client-side checks and still being able to edit.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Animating Object3D to move closer to the camera in a Three.js environment - currently functional, just requires adjustment of screen position

I have some code that animates an object towards the camera and resizes it to fit half of the screen var vFOV = camera.fov * Math.PI / 180; var ratio = 2 * Math.tan( vFOV / 2 ); var screen = ratio * (window.innerWidth * 0.6 / window.innerHeig ...

tinyScroll currently disabled

Attempting to implement the tinyscrollbar plugin found at Here is the code snippet: $('#nvl2 .content').html( '<div class="scrollbar">'+ '<div class="track">'+ ...

Save the value of a promise in a variable for future use in state management within a React-Native application

let storage = AsyncStorage.getItem('@location_data').then(data => data) const MainApp = () => { let [currentLocation, setCurrentLocation] = useState(storage); The current situation is that the storage variable holds a promise. How can ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

Creating a binary tree in vanilla JavaScript and styling it with HTML and CSS

I'm facing a challenge with my homework. I am required to convert my JavaScript binary tree into HTML and CSS, strictly using vanilla JavaScript without any HTML code. I have the tree structure and a recursive function that adds all the tree elements ...

Ways to utilize built-in features from a Java library that has been incorporated

I have embarked on a project to create a Nativescript wrapper for a Java library in order to harness its functionalities for a Nativescript application. Despite the lack of detailed articles on this topic, I have decided to turn this into a plugin wrapper ...

Tips for accurately measuring the height of a single table cell

I am facing an issue with a table that I have set up. Here is the code: <table> <tr> <td id='tdleftcontent' style='border:1px solid red;'> <asp:Label ID='lbl' runat="server"></asp:Label> < ...

Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays: Array One [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' } ] Array Two [ { name: &apos ...

The prompt "npm run build" command resulted in a 126 Vercel exit status

While attempting to upload my website with Webpack to Vercel from the repository, I encountered an error during the build process: Skipping build cache, deployment triggered without cache. Cloning completed: 2.089s Running "vercel build" Vercel CLI 31.2.3 ...

The onblur event is triggering prior to the value being updated

There are two input fields within a <form> element. I am trying to retrieve the value of one input field (dpFin) once it has been changed. The issue is that when I attempt to get the new value inside the event using var endDt = document.getElementByI ...

Delaying event listeners in Angular.js by using setTimeout within a factory or service

In order to delay the first iteration of the broadcast until the controller's $watchCollection is ready, I attempted using setTimeout() but it did not work as expected. Even trying with $timeout yielded the same result. What could be causing this issu ...

Transferring Data from Mod_rewrite to PHP using HTML and JavaScript for the User Interface

My web application has two components: the front end built with HTML, JavaScript/jQuery, and the back end using PHP. In its previous state, it utilized unsightly URLs such as host/app/Page.php?userid=1... definitely not aesthetically pleasing! But with a ...

Best practices for retrieving information from the user interface

My journey with NextJS has been a learning experience as I navigate connecting the frontend to the backend. Initially, I attempted to create a Restful API for CRUD operations from the frontend, but encountered authentication issues that left me puzzled. A ...

Create dynamic HTML files using Express, EJS, and FS, and deliver them using Nginx as the server instead of relying

Imagine a scenario where we have a JSON object: [ { "id": 1, "title": "Title 1", "description": "Description 1" }, { "id": 2, "title": "Title 2", ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

Packager freezing after running npm audit and the component directory is nonfunctional

Greetings, To begin with, I would like to acknowledge that this issue may have been addressed in previous posts, but despite following suggestions on Stack Overflow and GitHub, I am still facing two specific problems. Here are the issues I am encounterin ...

Is there a way to verify the content inside the :before selector using Jasmine within an Angular 6 application?

Looking to test whether the content of a label changes based on the checkbox being checked using Jasmine in an Angular 6 project. Is this feasible? Code snippet: HTML <input id="myCheck" class="checkbox" type="checkbox" /> <label for="myCheck" ...

Is there a way to enable verbose logging using the `System.Diags...Trace` feature?

Back in 2005, I stumbled upon the complexities of tracing with the System.Diagnostics namespace. Opting for log4net and NLog ever since, I see that Windows Azure Websites now rely on good old Trace. Proudly utilizing abstractions and IoC, I'm craftin ...

Preventing the negative consequences of being colorblind through programming techniques

My experience as a web developer has taught me that poor color contrast on a website can severely impact revenue. I am determined to change this, but have encountered an issue. On my site, there is a section where users can select a color and see it displa ...

The function createVNode does not exist in the context of Vue integrated with Laravel

I've been attempting to replicate a component rendering based on an online example. While it works smoothly in a sample project, it crashes when applied to the official codebase. Here is the content of the blade file being rendered: <html lang=&q ...