【问题标题】:How to pass data to _Layout.cshtml如何将数据传递给 _Layout.cshtml
【发布时间】:2017-08-28 00:22:14
【问题描述】:

At _Layout.cshtml used by all pages, when any background image is selected, I want to display the selected picture.但是,很遗憾,我不知道如何将这些数据传递给 _Layout.cshtml。

AT _Layout.cshtml

<style type="text/css">
        #body-bg {
            background-image: url('//I want to change here');
        }
</style>

我该怎么办?从任何控制器,这些数据都应该传递给 _Layout.cshtml,但是如何?

【问题讨论】:

  • 您可以使用包含该属性的基本视图模型,或使用ViewBagViewData 传递它
  • 根据您的处理方式,您也可以使用具有默认值的模板。 (即@RenderSection(...)

标签: c# asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

最稳健的方法是使用基本视图模型类并放置一个字符串属性来保存图像路径:

模型类

public class BaseViewModel
{
    public string BackgroundImage { get; set; }
}

_Layout.cshtml

@model BaseViewModel
<!DOCTYPE html>
<html>
<head>
     <!-- other styles, meta tags, etc. -->
     <style type="text/css">
     #body-bg {
         background-image: url('@Model.BackgroundImage');
     }
</head>
<body>
     <!-- body part -->
     @RenderBody()
</body>
</html>

如果您使用相对路径(例如 ~/Images/Selected.png)而不是绝对路径来引用图像路径,请使用带有字符串属性的 UrlHelper.Content 作为参数:

#body-bg {
     background-image: url('@Url.Content(Model.BackgroundImage)');
}

别忘了在控制器动作方法中设置viewmodel的字符串属性:

public class HomeController : Controller
{
    // other stuff
    return View(new BaseViewModel { BackgroundImage = "/path/to/image.png" });
}

注意:除了视图模型之外,您还可以使用 ViewBagViewData(它们都会自动传递给视图),方法是将 Model 更改为 ViewBag/ViewData

// View (CSS)
#body-bg {
    background-image: url('@ViewBag.BackgroundImage');
}

// Controller
public class HomeController : Controller
{
    // other stuff
    ViewBag.BackgroundImage = "/path/to/image.png";
    return View();
}

注意ViewBag 是动态的,可能需要额外检查以防止在使用ViewBag 属性时抛出NullReferenceException

参考资料:

Passing Data to Views (MS Documentation)

Pass data to layout that are common to all pages

Passing Data to a Layout Page

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-03
    • 2010-10-22
    • 2021-05-29
    • 2019-05-08
    相关资源
    最近更新 更多