【问题标题】:Adding a reusable block of code in Webmatrix在 Webmatrix 中添加可重用的代码块
【发布时间】:2013-12-04 14:32:23
【问题描述】:

我创建了一个 SQL 查询,通过检查查询字符串和 UserID 是否返回计数 1,来检查用户是否拥有数据库中的记录。这是下面的代码,它工作得非常好:

@{
Layout = "~/_SiteLayout.cshtml";

WebSecurity.RequireAuthenticatedUser(); 

var db = Database.Open("StayInFlorida");

var rPropertyId = Request.QueryString["PropertyID"];
var rOwnerId = WebSecurity.CurrentUserId;

var auth = "SELECT COUNT (*) FROM PropertyInfo WHERE PropertyID = @0 and OwnerID = @1";
var qauth = db.QueryValue (auth, rPropertyId, rOwnerId);
}

@if(qauth==0){
<div class="container">
    <h1>You do not have permission to access this property</h1>
</div>
}
  
else {
    SHOW CONTENT HERE
}

问题是我需要在至少 10 个不同的页面上应用此检查,将来可能更多?我完全赞成使用可重用的代码,但我不确定如何编写一次,并在需要的每一页上引用它。我已经尝试在中间嵌套布局页面的代码块中执行此操作,但我遇到了错误。关于什么是最好的方法的任何建议?还是我必须将其复制并粘贴到每一页?

【问题讨论】:

    标签: layout razor webmatrix


    【解决方案1】:

    “剃刀”方式是使用函数 (http://www.mikesdotnetting.com/Article/173/The-Difference-Between-@Helpers-and-@Functions-In-WebMatrix)。

    将以下内容添加到 App_Code 文件夹中名为 Functions.cshtml 的文件中:

    @functions {        
        public static bool IsUsersProperty(int propertyId, int ownerId)
        {
            var db = Database.Open("StayInFlorida");
            var sql = @"SELECT COUNT (*) FROM PropertyInfo 
                        WHERE PropertyID = @0 and OwnerID = @1";
            var result = db.QueryValue (sql, propertyId, ownerId);
            return result > 0;
        }
    }
    

    然后在您的页面中:

    @{
        Layout = "~/_SiteLayout.cshtml";
        WebSecurity.RequireAuthenticatedUser(); 
    
        var propertyId = Request["PropertyID"].AsInt();
        var ownerId = WebSecurity.CurrentUserId;
    }
    
    @if(!Functions.IsUsersProperty(propertyId, ownerId)){
    <div class="container">
        <h1>You do not have permission to access this property</h1>
    </div>
    }
    
    else {
        SHOW CONTENT HERE
    }
    

    【讨论】:

    • 哇,我不知道你可以使用这样的函数,包括其中的查询。这将为我节省很多编码。我将不得不回顾我的代码“功能化”一切。工作一种享受。我也会仔细阅读您网站上的文章。非常感谢(再次)
    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 2015-08-04
    • 2015-01-31
    • 1970-01-01
    • 2012-01-17
    • 2019-01-29
    • 1970-01-01
    相关资源
    最近更新 更多