在我的Visual Studio项目中,我有一个存储图像的文件夹。此映像的路径存储在SQL Server数据库中,并尝试在视图中显示此图像。根据我迄今为止所做的研究,需要创建一个HTML帮助程序,我可以使用它。我如何将路径传递给助手,以便在我的视图中,在内容显示下呈现?
查看
@Html.DisplayFor(modelItem => item.contentDisplay)
辅助
public static class CustomHtmlHelper
{
public static IHtmlString Image(this HtmlHelper helper, string src)
{
TagBuilder tb = new TagBuilder("img");
tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}
控制器
private dbmb17adtEntities db = new dbmb17adtEntities();
// GET: tbl_Post2
public ActionResult Index()
{
var tbl_Post = db.tbl_Post.Include(t => t.tbl_User);
return View(tbl_Post);
模型
public partial class tbl_Post
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public tbl_Post()
{
this.tbl_Comment = new HashSet<tbl_Comment>();
this.tbl_Tag = new HashSet<tbl_Tag>();
}
public int Id { get; set; }
public string title { get; set; }
public string content { get; set; }
public string contentDisplay { get; set; }
public string tags { get; set; }
public Nullable<System.DateTime> createTime { get; set; }
public Nullable<System.DateTime> updateTime { get; set; }
public Nullable<int> commentCount { get; set; }
public int authorId { get; set; }
public Nullable<int> likeCount { get; set; }
我如何在我的视图中使用帮助器(如果它确实是正确的)?
答案 0 :(得分:2)
你可以尝试
@foreach (var items in tbl_Post)
{
<img src="@Url.Content(items.contentDisplay)" alt="" />
}
答案 1 :(得分:1)
我正在使用HttpPostedFileBase将文件从视图发布到控制器操作。
在视图中,请勿忘记enctype = "multipart/form-data"
您正在使用的表单。
[HttpPost]
public async Task<ActionResult> AddImage(HttpPostedFileBase postedFile)
{
string path = Server.MapPath("~/Content/Images/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
//myVm.Path = path + Path.GetFileName(postedFile.FileName);
//this is how you can save the virtual path in your property
return RedirectToAction("Index");
}
这就是我在视图中显示它的方式
<img src="@Url.Content("~/Content/Images/" + @Path.GetFileName(item.Path))" />
答案 2 :(得分:0)
看起来你实际上可能会这样做:
@Html.Image(item.contentDisplay)
您定义的是一种扩展方法,因此您可以像通常使用HtmlHelper方法一样使用它。
您在DisplayFor上的初始镜头是针对不同的场景,特别是当您为特定模型类定义了自定义模板视图时,您希望MVC根据模型类识别和使用它。
答案 3 :(得分:-1)
@foreach (var item in db.tblStudents)
{
<tr>
<td><img src="~/images/@item.ImageUrl" width="100" height="100" /></td>
<td>@item.FirstName</td>
<td>@item.LastName</td>
</tr>
}