剃刀页面核心本地方法

时间:2017-11-03 13:43:59

标签: asp.net-core asp.net-core-mvc razor-pages

直接从HTML调用剃刀页面中的@functions {}部分中的方法是否可以?这似乎工作正常,比调用API容易得多,但我想知道这是否存在缺点(安全性,性能等)?

例如,在代码中......

@functions {

public class Tickets: PageModel
{
    public ApplicationDbContext _db { get; set; }
    public Tickets(ApplicationDbContext db)
    {
        _db = db;
    }

    public void OnGet()
    {
    }

    public string GetTickets(int Top) //--> THIS IS THE METHOD I AM CALLING
    {
        var data = _db.Tickets.OrderByDescending(x => x.CreatedAt).Take(Top);
        var jdata = JsonConvert.SerializeObject(data.ToList());
        return jdata;
    }
}
}

HTML ...

<div class="card alert-warning" v-for="ticket in tickets">
    <div class="card-body">
        <h4 class="card-title">{{ticket.TicketSubject}}</h4>
        <a href="#" class="card-link">Card link</a>
        <a href="#" class="card-link">Another link</a>
    </div>
</div>

@section Scripts {

<script>
    new Vue({
        el: '#app',
        data: {
            dismissSecs: 5,
            dismissCountDown: 5,
            tickets: @Html.Raw(Model.GetTickets(100)),  //-->THIS WORKS, BUT IT IS OK TO USE LIKE THIS?
            xx: ''
        }
 })
 </script>

 }

1 个答案:

答案 0 :(得分:0)

它的工作原理是因为我相信在呈现页面时调用该方法并且您传入了常量值。如果没有涉及AJAX代码,它将不会自动执行更新客户端之类的操作。

但是为了回答你的问题,我认为'更正确'的方法是在OnGet中设置绑定属性并引用客户端

public class Tickets : PageModel
{
    public ApplicationDbContext _db { get; set; }
    public Tickets(ApplicationDbContext db)
    {
        _db = db;
    }

    [BindProperty]
    public string TicketData { get; set; }

    public void OnGet()
    {
        TicketData = GetTickets(100);
    }

    public string GetTickets(int Top) 
    {
        var data = _db.Tickets.OrderByDescending(x => x.CreatedAt).Take(Top);
        var jdata = JsonConvert.SerializeObject(data.ToList());
        return jdata;
    }
}