Javascript 如何进行基于权限的UI显示
更新- 我根据新信息修改了问题: 我们有一个在网格中返回搜索结果的小应用程序。只有一个控制器操作,因为这是应用程序所做的全部操作。但是,我们希望根据用户权限隐藏某些数据。例如,基于用户权限,我将StockSource列隐藏为HTML,如下所示:Javascript 如何进行基于权限的UI显示,javascript,jquery,asp.net-mvc-4,jquery-datatables,Javascript,Jquery,Asp.net Mvc 4,Jquery Datatables,更新- 我根据新信息修改了问题: 我们有一个在网格中返回搜索结果的小应用程序。只有一个控制器操作,因为这是应用程序所做的全部操作。但是,我们希望根据用户权限隐藏某些数据。例如,基于用户权限,我将StockSource列隐藏为HTML,如下所示: <th>Name</th> @if (Model.UserCanSeeThis) { <th>StockSource</th> } <th>SomeOtherColumn</th
<th>Name</th>
@if (Model.UserCanSeeThis)
{
<th>StockSource</th>
}
<th>SomeOtherColumn</th>
问题是我不能将“StockSource”设置为不可见,因为如果用户没有权限,则没有可设置为null的StockSource列。你知道怎么控制吗 我仍然会在服务器端这样做。只是不要设置变量StockSource js看起来像
if (data != null) {
/* Get data for the given row */
out = "<table cellpadding='5' cellspacing='0' border='0' style='padding-left:50px;'>";
out += "<tr><td>Name:</td><td>" + data["Name"] + "</td></tr>";
if (data["StockSource"])
out += "<tr><td>Stock Source:</td><td>" + data["StockSource"] + "</td></tr>";
out += "</table>";
}
if(数据!=null){
/*获取给定行的数据*/
out=“”;
输出+=“名称:”+数据[“名称”]+”;
如果(数据[“股票来源”])
out+=“股票来源:“+数据[“股票来源”]+”;
out+=“”;
}
当您使用MVC时,我建议您将模型传递回创建表的视图。这样,您可以以比目前更干净的方式创建所需的列,因为当前的表生成代码不容易维护
在您的视图中,您只需检查列是否需要并呈现它,如果不需要,则不呈现它。我可以想到的一种方法是,您可以创建一个内联脚本来处理视图页面上的aoColumns
<script>
//Preload with the first column since you know it will always be there
var includedColumns = [{ "mData": "Name" }];
@if (Model.UserCanSeeThis)
{
//Add stock source when the user can see
includedColumns.push({ "mData": "StockSource" });
}
//Add additional columns
includedColumns.push({ "mData": "SomeOtherColumn" });
</script>
你是对的,我通常会这样做,但在本例中,所有调用都是从js直接调用WebAPI的,因此唯一使用的控制器操作是最初呈现搜索页面的操作。我喜欢这样。不幸的是,我发现我真正需要控制的地方是我将问题改为上面的“aoColumns”正在构建的地方。我的错。有什么想法吗?最后做了类似的事情。谢谢你,布雷特!
<script>
//Preload with the first column since you know it will always be there
var includedColumns = [{ "mData": "Name" }];
@if (Model.UserCanSeeThis)
{
//Add stock source when the user can see
includedColumns.push({ "mData": "StockSource" });
}
//Add additional columns
includedColumns.push({ "mData": "SomeOtherColumn" });
</script>
$('#grdSearch').dataTable( {
"bProcessing": true,
"sAjaxSource": uri,
"fnServerData": function(sSource, aoData, fnCallback, oSettings) {
oSettings.jqXHR = $.ajax(
{
type: "POST",
url: sSource,
data: JSON.stringify(BuildSearchParams()),
contentType: "application/json",
dataType: 'json',
success: function (data) {
if (typeof data["error"] == "undefined") {
fnCallback(data);
} else {
alert(data["error"]);
}
}
});
},
"aoColumns": includedColumns });