2017-11-20 1 views
3

내 Visual Studio 프로젝트에서 이미지를 저장하는 폴더가 있습니다. 이 이미지의 경로는 SQL Server DB에 저장되어 있으며이 이미지를 뷰에 표시하려고합니다. 지금까지 한 연구에서 HTML 도우미를 만들어야합니다. 헬퍼에게 경로를 전달하여 내보기에서 콘텐츠 표시 아래에 렌더링 할 수 있습니까?ASP MVC 5 이미지 디스플레이

보기

@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

에 표시하는 방법입니다? 샘플 값은 어떻게 생깁니 까? 또한 이미지 저장 디렉토리가 앱에 있습니까? – Shyju

답변

1

당신은 내가 조치를 컨트롤러에 뷰에서 파일을 게시 할 HttpPostedFileBase을 사용하고

@foreach (var items in tbl_Post) 
{ 
    <img src="@Url.Content(items.contentDisplay)" alt="" /> 
} 
+0

감사합니다. 매우 가까웠습니다. – CyberCube

+0

CyberCube

+0

도움이 될만한 해결책이 있으면 알려 주시고 향후 독자를 돕기 위해 허용으로 표시해주십시오. – Izzy

0

그것은 당신이 실제로이 작업을 수행 할 수있을 것 같습니다 당신이 일반적으로 Html 헬퍼 방법을 사용 하듯이 사용할 수 있도록

@Html.Image(item.contentDisplay) 

는 당신이 정의하는 것은, 확장 방법이다.

DisplayFor의 초기 샷은 다른 시나리오, 특히 사용자가 소유 한 특정 모델 클래스에 대한 사용자 지정 템플릿 뷰를 정의하고 MVC가 모델 클래스를 기반으로 식별하고 사용하게하려는 경우에 사용됩니다.

1

을 시도 할 수 있습니다. 보기에서 사용중인 양식에 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"); 
      } 

는이 내가 당신을`contentDisplay` 속성에 무엇을 저장하는 뷰

<img src="@Url.Content("~/Content/Images/" + @Path.GetFileName(item.Path))" />