Search code examples
layoutrazorwebmatrix

Adding a reusable block of code in Webmatrix


I have created an SQL query which checks if a user owns a record in the database, by checking if the querystring and UserID return a count of 1. This is the code below, and it works absolutely fine:

@{
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
}

The problem is that I need to apply this check on at least 10 different pages, maybe more in the future? I'm all for using reusable code, but I'm not sure how I can write this once, and reference it on each page that it's needed. I've tried doing this in the code block of an intermediate nested layout page, but I ran into errors with that. Any suggestions as to what would be the best approach? Or am I going to have to copy and paste this to every page?


Solution

  • The "Razor" way is to use a Function (http://www.mikesdotnetting.com/Article/173/The-Difference-Between-@Helpers-and-@Functions-In-WebMatrix).

    Add the following to a file called Functions.cshtml in an App_Code folder:

    @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;
        }
    }
    

    Then in your page(s):

    @{
        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
    }