gpt4 book ai didi

jquery - 如何使用 jQuery 在 ASP.NET-MVC3 中动态加载图像

转载 作者:行者123 更新时间:2023-12-01 07:31:46 25 4
gpt4 key购买 nike

在我的 MVC3 _Layout.cshtml 页面上,我显示了这样的横幅图像

    <body>
<div id="page">
<div id="nonFooter">
<div id="header">
<img id="headerBanner" src="@Url.Content("~/Content/Images/banner.jpg")" alt="Banner" />
</div> ....

足够简单。

我想要做的是为使用该网站的每个客户端显示不同的图像,这很可能由网址决定,例如:www.mysite.com/clientA/Home(clientA 确定要使用哪个图像)

本质上,所需的功能有点像 CMS,但我们不需要完整的 CMS,我们只需要替换一些图像和颜色。

所以问题是最好的方法是什么?

到目前为止我的想法是使用 jQuery 像这样更新 src

<script type="text/javascript">
$(document).ready(function () {
$('#headerBanner').attr('src', whatToPutHere? );
});

但我一直坚持 whatToPutHere 的“最佳实践”。

难道是……

  • 在服务器端代码中放入 ViewBag 中的图像(例如@ViewBag.BannerImage)?
  • 将图像放入 ViewModel 中?
  • 某种服务器调用来获取/加载图像(确定要使用哪个图像的逻辑必须在服务器端)...(但这会是另一次往返吗?)?
  • ...另一种方法?

非常感谢任何帮助:-)

最佳答案

我将仅使用服务器端代码来生成用户特定的图像 URL。我不会使用 ViewBag 或 model 将数据传递给 View,因为它位于 _Layout 页面中。为了简单起见,在下面的示例中使用了静态方法。如果您担心单元测试,则需要使用非静态方法进行重构。

在_Layout.cshtml中:

<img src="@AccountServices.BannerUrl" alt="Banner" />

在AccountServices.cs中

public class AccountServices
{
public static string BannerUrl
{
get{
// Your code to form the image URL, may be the following:
var bannerPathTemplate = "/images/banners/user-{0}.jpg";
var user = CurrentUser;
if (user != null)
{
return string.Format(bannerPathTemplate, user.Id);
}
return string.Format(bannerPathTemplate, "unauthorized");
}
}

const string sessionKeyUser = "session-current-user";

public static User CurrentUser
{
get{
if (HttpContext.Current.Session[sessionKeyUser]==null){
// HERE insert code to get the current **user** object from db
HttpContext.Current.Session[sessionKeyUser] = user;
}
return (User)HttpContext.Current.Session[sessionKeyUser];
}
}

}

我会使用的另一种获取横幅 HTML 的方法是 @Html.RenderAction("your action", "your controller")。

关于jquery - 如何使用 jQuery 在 ASP.NET-MVC3 中动态加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5617575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com