layout - 在 Webmatrix 中添加可重用的代码块

标签 layout razor webmatrix

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

最佳答案

“Razor”方式是使用函数 (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
}

关于layout - 在 Webmatrix 中添加可重用的代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20098654/

相关文章:

java - 哪个布局管理器适合我的设计?

java - 为什么边界在此 GUI 上不起作用

css - 按钮与 float 和 PartialView 不在同一级别

javascript - 将参数从 View 传递到 Controller Razor

c# - 当前上下文中不存在名称 'Database'?

webmatrix - webmatrix 是否适合 "private"Web 应用程序?

android - 如何让布局监听器忽略其顶部的 View - android

layout - libgdx 表仅在右下区域布置组件

c# - 通过 ajax 加载的 ASP.NET MVC 表单多次提交

c# - 我可以在 .cs 文件中实现什么 using 指令来让我使用 "WebPageExecutingBase.Href()"方法?