dqoqnmb163241 2016-03-16 11:37
浏览 138
已采纳

在MVC主页中使用数据库数据

Suppose i'd like to display title of latest articles. for particular Views , we use controllers to handle that. but for common section of pages like header or footer , How to display data(latest articles) from database (within MVC rules) ? Note: I use php

Please check my approach:

app class:

<?php
class app{
    public static function appLoader($app){
        include 'apps/'.$app.'/'.$app.'.class.php';
        new $app;
    }
}

test.class.php :

class test extends app{
    function __CONSTRUCT(){
        return 'Hello World';
    }
}

footer.php:

<footer>
<?php echo app::appLoader("test") // returns 'Hello World' ?>
</footer>
  • 写回答

1条回答 默认 最新

  • drslez4322 2016-03-16 12:10
    关注

    Note: This is w.r.t .Net MVC

    If you are following MVC pattern - then there's a concept of "Partial Views" - which is just like user controls, and it can be placed in the main page.

    Partial view is also an html page which might just div, no html body head etc because it will be rendered inside main html page

    You might need to verify the syntax for Partial Views with PHP. The concept remains same for MVC.

    There are various ways to display partial views.

    One popular way is the one where Partial view is called by its action method - which will ultimately display the result(the partial view).

    The Action method will return a "_Footer" Partial view - where you can put your HTML Code of displaying the data from DB(the latest articles).

    The partial view must bind from the list of articles. which is popularly known as Strong Type Binding in .Net - which is nothing but mapping the view(HTML page) to a specific class to display the data from that class.

    For your reference the below example can be referred(in .Net):

    Create a partial view for footer(_Footer) and call it using Action Method(RenderAction - .Net). This action method can fetch the data from database and display in the partial view(_Footer)

    The call to the action method be like from the view(html page):

        @{ Html.RenderAction("Index", "Footer", new { Area = "Common", id}); }
    

    And the Controller and action method like:

        public class FooterController : Controller
        {
            public ActionResult Index(int id)
            {
                var vm = new FooterViewModel
                {
                    Id = id
                };
    
                return this.PartialView("_Footer", vm);
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?