在我的Visual Studio项目中,我有一个文件夹,用于存储图像。此图像的路径存储在 SQL Server DB 中,并且尝试在视图中显示此图像。从我到目前为止所做的研究中,需要创建一个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; }
在我看来,我如何使用帮助程序(如果它确实正确(?
试试
@foreach (var items in tbl_Post)
{
<img src="@Url.Content(items.contentDisplay)" alt="" />
}
我正在使用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))" />
看起来您实际上可以做到这一点:
@Html.Image(item.contentDisplay)
您定义的是一个扩展方法,因此您可以像通常使用 HtmlHelper 方法一样使用它。
您在 DisplayFor 上的初始镜头是针对不同的方案,特别是当您为拥有的特定模型类定义自定义模板视图时,您希望 MVC 根据模型类识别并使用该视图时。
@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>
}