【问题标题】:How to display an image from path in MVC 4?如何在 MVC 4 中显示路径中的图像?
【发布时间】:2014-07-23 16:51:47
【问题描述】:

在开始之前,我在这里看到过这个问题,我已经按照这里给出的答案和示例进行操作:

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

但是当我这样做时

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

我收到一个错误

来源错误

   [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="..." />

它会正常显示图像,没有错误。

【问题讨论】:

  • 您是否真的将模型实例传递给控制器​​中的视图?
  • null 是哪个对象?您如何将模型提供给视图?

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


【解决方案1】:

怀疑您忘记向视图提供模型实例。

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,这将完全消除提供视图模型的需要:

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="..." />

【讨论】:

  • 您好,您分享的所有方法都有效,谢谢。现在你会推荐什么更好的方法来做到这一点?
  • @Johhan 这真的取决于。但通常第一种方法会更灵活。如果回答了您的问题,请考虑将我的回答标记为已接受:)
【解决方案2】:

在你的控制器中你应该有这样的东西:

 ActionResult Index(){
 return View(new ProfileImages());
 }

【讨论】:

    【解决方案3】:

    也许您没有将模型传递给视图:

    var model = new ProfileImages();
    return View(model);
    

    【讨论】:

    • 做到了,现在我想知道,我需要对每个视图都做同样的事情吗?
    • 没有。对于帖子,如果没有指定收到的模型,将自动传递。
    • 但是在您的情况下,由于该字段是只读的,因此该值需要在隐藏字段中以保留在帖子之间。
    猜你喜欢
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2014-06-21
    相关资源
    最近更新 更多