@model for _layout.cshtml on MVC4?

后端 未结 4 1290
眼角桃花
眼角桃花 2021-01-02 09:42

I was wondering if there\'s a way to specify a model for the _layout.cshtml file, i\'ve seen lots of posts with the basic same question with people replying with \"alternati

相关标签:
4条回答
  • 2021-01-02 09:59

    You should delegate the parts of your layout that "need a model" to a separate controller using partial views and RenderAction:

    @Html.RenderAction("SomeAction", "LayoutController")
    

    Have LayoutController.SomeAction return a PartialViewResult, which you can then strongly type to a model.

    0 讨论(0)
  • 2021-01-02 10:00

    Even though you already accepted an answer, based on your saying you are just pulling an image URL you should do it using JQuery, not a model.

    This code is untested, apologies for that. Feel free to point out if I typed a bug. The HTML element containing the background image has the id="url" attribute so the selectors work.

    Controller

    [HttpGet]
    public string GetSessionUrl()
    {
        //logic to detmine url
        return url;
    }
    

    JQuery

    $(document).ready(function () {
        var $url = $('#url');
        var options = {
            url: "/Home/GetSessionUrl",
            type: "get",
            async:false
        };
    
        $.ajax(options).done(function (data) {
            $url.attr('src', data);
        });
    });
    
    0 讨论(0)
  • 2021-01-02 10:00

    You can add BaseModel to _Layout.

    @model BaseModel
    

    Then all models inherit from that BaseModel class.

    public class MyModel : BaseModel
    {
    }
    

    As others stated, it is not a good practice. If your model forgets to inherit from BaseModel, it'll throws exception at run time. However, it is up to you.

    0 讨论(0)
  • 2021-01-02 10:00

    In BaseController you can declare any model as property.

    public class BaseController : Controller
    {
        public BaseController ()
        {
            MyTag = new TagModel ();  // or get db, take any value from there           
        }
    
        public TagModel MyTag { get; set; }
    }
    

    In action:

    ViewBag.MyTag = MyTag ;
    

    And in _Layout.cshtml, you can use

    @{
      var myTag = (TagModel)ViewBag.MyTag;
    }
    
    0 讨论(0)
提交回复
热议问题