MVC3 Partial Views

前端 未结 3 1947
自闭症患者
自闭症患者 2021-01-15 03:52

Still Learning MVC3, EF. For now I am connecting to MySql but I believe that will not be relevant. For simplicity, I decided to use one database for my test application and

相关标签:
3条回答
  • 2021-01-15 04:17

    You could do the following:

    Controller:

    public ActionResult Home()
    {
      IEnumerable<MyDateRecords> myData = LinqQueryToGetAllTheDataUnFiltered();
      ViewData.Model = new MyViewData { MyData = myData; }
      return View();
    }
    

    ViewModel class:

    public class MyViewData
    {
      List<MyDataRecords> MyData { get; set; }
      List<MyDataRecords> News { get { return MyData.Where(m => m.Category = "News"); } }
      List<MyDataRecords> Events { get { return MyData.Where(m => m.Category = "Events"); } }
    }
    

    View:

    @model MyViewModel
    
    @Html.Partial("NewsPartial", Model.News)
    @Html.Partial("EventsPartial", Model.Events)
    

    Partial:

    @model IEnumerable<MyDataRecord>
    

    This way we only queried for the data once and just passed a different set to each partial

    0 讨论(0)
  • 2021-01-15 04:19

    For an uncomplicated way of presenting this type of data, what you are doing is fine. You should look at the OutputCacheAttribute for any PartialView Method you use on your Controller.

    0 讨论(0)
  • 2021-01-15 04:27

    This is pretty inefficient. But it's good that you noticed this because querying that database is often the bottleneck in any given request.

    For starters you should retrieve that data into a dictionary or model and then pass it to the partial views to render similar to what Bassam outlined. Ideally, this should be taken care of in the Controller to stick to the MVC paradigm and then passed to the main view, which would then pass the appropriate data to the partial views.

    Once you get more advanced/familiar with ASP.NET MVC, you can start looking into caching. I'd stay away from caching for right now since it get somewhat tricky if you have data that is rapidly changing since you need to start worrying about updating/synchronizing/etc.

    0 讨论(0)
提交回复
热议问题