gpt4 book ai didi

c# - 如何在 MVC 4 中显示来自路径的图像?

转载 作者:行者123 更新时间:2023-11-30 16:11:02 25 4
gpt4 key购买 nike

在开始之前,我之前在这里看到过这个问题,并且我遵循了这里给出的答案和示例:

how to display image from path in asp.net mvc 4 and razor view

但是当我这样做的时候

<img src="@Url.Content(Model.ImagePath)" class="dker" alt="..." />

我得到一个错误

Source Error

   [No relevant source lines]
[NullReferenceException: Object reference not set to an instance of an object.]

在我的模型中:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace NSProfileImages
{
public class ProfileImages
{
public string ImagePath
{
get
{
return "~/Assets/Images/user_images/avatars/123@123.com.jpg";
}
}
}
}

查看:

@model NSProfileImages.ProfileImages

<img src="@Url.Content(Model.ImagePath)" class="dker" alt="..." />

如果我这样做

<img src="~/Assets/Images/user_images/avatars/123@123.com.jpg" class="dker" alt="..." />

它将正常显示图像并且没有错误。

最佳答案

怀疑您忘记为 View 提供模型实例。

public ActionResult Index()
{
// here we instantiate the type and supply it to the view.
ViewData.Model = new ProfileImages();
return View();
}

或者,您可以通过 View 方法提供模型实例,如下所示:

 return View(new ProfileImages());

请注意,在这种情况下,您可以将模型属性设置为 static,这将完全消除提供 View 模型的需要:

public class ProfileImages {
public static string ImagePath {
get {
return "~/Assets/Images/user_images/avatars/123@123.com.jpg";
}
}
}
...
<img src="@Url.Content(NsProfileImages.ProfileImages.ImagePath)"
class="dker" alt="..." />

关于c# - 如何在 MVC 4 中显示来自路径的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24916419/

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