其他分享
首页 > 其他分享> > CodeGo.net>如何显示图像从MVC 4中的路径?

CodeGo.net>如何显示图像从MVC 4中的路径?

作者:互联网

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

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

06001

在我的模型中:

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

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

解决方法:

我怀疑您忘记向视图提供模型的实例.

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());

请注意,在这种情况下,您可以很好地将model属性设为静态,这将完全不需要提供视图模型:

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

标签:razor,asp-net-mvc-4,c,asp-net-mvc
来源: https://codeday.me/bug/20191121/2051965.html