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

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

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

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/

相关文章:

c# - LINQ:无法将类型 'System.Int32' 转换为类型 'System.Object'

c# - 正则表达式与预期不匹配

asp.net-mvc - 有条件的 ASP.NET MVC Razor 部分

c# - 禁用 DropDownList razor mvc

c# - 如何从 C# 中的两个 List<String> 中获取移动组合?

c# - ASP.NET 2.0-4.0 Web 应用程序的初始启动速度极慢。

c# - 停止需要很长时间的操作使负载均衡器超时

c# - 我应该如何依赖 Session

html - 当用户从下拉列表中选择一个项目时,必须在 mvc 4 中为该用户删除该项目

database - EF 代码优先建模将如何影响数据库中已有的数据