简体   繁体   English

如果登录的用户角色为“关联”,则阻止javascript函数生成删除操作链接

[英]Prevent javascript function from generating delete action links if a logged in user role is Associate

I got two different roles, Admin and Associate. 我有两个不同的角色,管理员和助理。

An Admin should be able to delete a product while an Associate should not be able to delete a product. 管理员应该能够删除产品,而助理应该不能删除产品。

I know how to configure this in the View by not showing the Delete Action Link for an logged in Associate user. 我知道如何通过不显示已登录的关联用户的“删除操作”链接来在“视图”中进行配置。 However I have also implemented an onkeydown ajax search functionality that returns a list of jsonobjects. 但是,我还实现了onkeydown ajax搜索功能,该功能返回jsonobjects列表。 These json-objects are a list of product objects that matches the searchstring and then immediately builds up the markup in the view. 这些json-objects是与搜索字符串匹配的产品对象的列表,然后立即在视图中建立标记。 This is done from a single javascript function. 这是通过单个javascript函数完成的。

The problem with this is that it now is hardcoded to generate delete action links, regardless of current logged in user role. 问题在于,无论当前登录的用户角色如何,现在都对其进行了硬编码以生成删除操作链接。 So in a way, I need to modify my javascript function so that it doesn't generate delete actionlinks if the current logged in user is an associate user. 因此,以某种方式,我需要修改我的javascript函数,以便如果当前登录的用户是关联用户,则它不会生成删除动作链接。

This is my function: 这是我的功能:

     function searchProduct() {

        var searchWord = $('#searchString').val();                                

        $.ajax({
            url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
            type: 'GET',
            datatype: 'json',
            contenttype: 'application/json',
            success: function (data) {

                $('.table tr:gt(0)').detach();
                $.each(data, function (i, item) {
                    $('.table').append('<tr>' +
                            '<td>' + item.Name + '</td>' +
                            '<td>' + item.Status + '</td>' +
                            '<td>' + item.Genre + '</td>' +
                            '<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> |' +
                            '<a href=/Product/Details/' + item.Value + '>Details</a> |' +
                            '<a href=/Product/Stock/' + item.Value + '>Stock</a> |' +
                            '<a href=/Product/Discount/' + item.Value + '>Discount</a> |' +                            
                            '<a href=/Product/Delete/' + item.Value + '>Delete</a>' +
                            '</td>' +
                            '</tr>'
                        );
                });
            }
        });
    }

Triggered by this in the View: 在视图中由此触发:

<div class="form-group">
            @Html.TextBox("searchString", "", new { onkeydown = "searchProduct();", onkeyup = "searchProduct();", onkeypress = "searchProduct();"})
            <input type="submit" value="Search" class="btn btn-default" onclick="searchProduct()"/>
        </div>

My Server code in the controller: 控制器中的“我的服务器”代码:

public JsonResult TextChangeEventSearch(string searchString)
    {
        var products = _productRepository.GetAll().ToList();            
        var result = products.Where(p => p.Name.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0).OrderByDescending(x => x.Status).ThenBy(y => y.Name);


        var jsonList = result.Select(p => new
        {
            Name = p.Name,
            Status = p.Status,
            Genre = p.Category.Name,
            Value = p.Id.ToString(),
            Warehouse = p.Stock
        });


        return Json(jsonList.ToList(), JsonRequestBehavior.AllowGet);
    }

I think that I need access to the current logged in user role in the javascript function. 我认为我需要访问javascript函数中当前登录的用户角色。 Then I might be able to add one if statement in the function that prevents it from generating delete action links in the view if it is an associate user that uses this function. 然后,如果它是使用此功能的关联用户,则可以在该功能中添加一个if语句,以防止它在视图中生成删除操作链接。

Where do I go next with this? 我下一步该去哪里? Any thoughts, explanations and help would be greatly appreciated. 任何想法,解释和帮助将不胜感激。

May be you can render the role of the current user in one hidden field on the page and then use the value of that field to decide if delete button should be rendered. 可能是您可以在页面上的一个隐藏字段中呈现当前用户的角色,然后使用该字段的值来决定是否应显示“删除”按钮。

@{
    Layout = Model.Layout;
    var isAssociate = Context.User.IsInRole("Associate"); //This is indicative and one of the approach of getting user role information at the client side. You can have your own mechanism to get the user's role information at the client side so that you can use it in your javascript.
}
    <input type="hidden" value="@isAssociate"/>

and your javascript call will look like as following. 并且您的javascript调用将如下所示。

    function searchProduct() {

                var searchWord = $('#searchString').val();                                
                var isAssociate = $('#isAssociate').val();

                $.ajax({
                    url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
                    type: 'GET',
                    datatype: 'json',
                    contenttype: 'application/json',
                    success: function (data) {

                        $('.table tr:gt(0)').detach();
                        $.each(data, function (i, item) {
                            var htmlContent = '<tr>' +
                                    '<td>' + item.Name + '</td>' +
                                    '<td>' + item.Status + '</td>' +
                                    '<td>' + item.Genre + '</td>' +
                                    '<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> |' +
                                    '<a href=/Product/Details/' + item.Value + '>Details</a> |' +
                                    '<a href=/Product/Stock/' + item.Value + '>Stock</a> |' +
                                    '<a href=/Product/Discount/' + item.Value + '>Discount</a> ';
                        if(isAssociate == "false")
                       {
                             htmlContent += |' + '<a href=/Product/Delete/' + item.Value + '>Delete</a>'
                       }

                       htmlContent += '</td>' + '</tr>'           
                       $('.table').append(htmlContent);
                });
            }
       }
});

NOTE : Here I am assuming that you have figured out a mechanism to identify the user role and you are able to store it so that it can be accessed in the view. 注意:在这里,我假设您已经找到了一种识别用户角色的机制,并且可以对其进行存储,以便可以在视图中对其进行访问。 If you don't have this then you need to figure out a way for that. 如果您没有此功能,则需要找出解决方法。

I am sure this will help you. 我相信这会对您有所帮助。

Thanks and regards, 谢谢并恭祝安康,

Chetan Ranpariya 切坦·兰帕里亚

you're on the right track. 您走在正确的轨道上。 the js needs to know! js需要知道! you could add a data attribute to the input, for example: 您可以将data属性添加到输入中,例如:

<input data-is-admin="false" ....>

and then check this attribute in the js. 然后在js中检查此属性。 and you'll propably want to authorize any delete on your server anyway. 并且您可能会想要授权服务器上的任何删除。

使用JavaScript获取数据后,您可以使用在线if语句仅显示管理员的删除按钮:

'...' + ( userRole == 'Admin' ? '[Delete button HTML]' || '') + '...'

It's been a while, but I got back to this issue many weeks later, and I solved it like this: 已经有一段时间了,但是很多周后我又回到了这个问题,我像这样解决了它:

At the top of the view: 在视图顶部:

@{
    ViewBag.Title = "Index";
    var isAdmin = Context.User.IsInRole("Admin");    
}

Javascript function: JavaScript函数:

function searchProduct() {

            var searchWord = $('#searchString').val();            
            var isAdmin = "@isAdmin";




            $.ajax({
                url: '/Product/TextChangeEventSearch?searchString=' + searchWord,
                type: 'GET',
                datatype: 'json',
                contenttype: 'application/json',
                success: function (data) {

                    $('.table tr:gt(0)').detach();
                    $.each(data, function (i, item) {
                        var htmlContent = '<tr>' +
                                    '<td>' + item.Name + '</td>' +
                                    '<td>' + item.Status + '</td>' +
                                    '<td>' + item.Genre + '</td>' +
                                    '<td>' + '<a href=/Product/Edit/' + item.Value + '>Edit</a> | ' +
                                    '<a href=/Product/Details/' + item.Value + '>Details</a> | ' +                                    
                                    '<a href=/Product/Discount/' + item.Value + '>Discount</a> ';                        
                        if (isAdmin.toString() === "True")
                        {
                            htmlContent += '| ' + '<a href=/Product/Delete/' + item.Value + '>Delete</a>'
                        }


                        htmlContent += '</td>' + '</tr>'           
                        $('.table').append(htmlContent);
                    });
                }
            });
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Javascript中的Firebase数据库中删除用户的信息(即使他/她当前未登录)? - How to delete a user's info(even if he/she is not currently logged in) from firebase database in javascript? 使用“ javascript://”作为链接来阻止操作是错误的还是不良的做法? - It is wrong or a bad practice to use “javascript://” as links to prevent action? 仅当用户登录时才运行 JavaScript 函数 - Django - Run JavaScript function only if user logged in - Django 防止用户更改特定列的值的javascript函数 - javascript function to prevent user from changing the value of a specific column 从Java脚本中的字符串生成函数 - Generating a function from a string in Javascript 如何防止用户登录后看到登录页面? - How to prevent user from seeing login page after logged in? 如果已经登录,则阻止用户返回浏览器(反应) - Prevent user from going back on browser if already logged in (react) Javascript在用户搜索时从数组生成内容 - Javascript generating content from an array on user search 暂停javascript异步功能直到用户操作 - Pausing javascript async function until user action 从 javascript 函数生成 django HTML URL - Generating a django HTML URL from a javascript function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM