2013-09-28 1 views
0

이미지 경로를 저장하는 컨트롤러의 포스트 백 이벤트에 뷰 백을 만들었습니다. 그런 다음 이미지 src 특성에서이 뷰 백 값을 사용했습니다. 그러나 이미지는 표시되지 않습니다.컨트롤러에서보기 백 값을 읽을 수 없습니다.

모델 : 이미지

을 업로드

public class FileManagement 
    { 
    public string FileName { get; set; } 
    public string Path { get; set; } 
     } 

코드

 [HttpPost] 
     public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file) 
     { 
     string email = User.Identity.Name; 

     if (file != null && file.ContentLength > 0) 
     { 
      var FileName = string.Format("{0}.{1}", Guid.NewGuid(), Path.GetFileName(file.FileName)); 
      var path = Path.Combine(Server.MapPath("~/Content/Uploads"), FileName); 
      file.SaveAs(path); 

     using (var session = DocumentStore.OpenSession("RavenMemberShip")) 
      { 

       var query = from q in Session.Query<Registration>() where q.Email == email select q; 
       if (query.Count() > 0) 
       { 
        foreach (var updated in query) 
        { 
         updated.FileName = FileName; 
         updated.Path = path; 
         session.SaveChanges(); 

        } 
       } 
      } 
     } 
     else ModelState.AddModelError("", "Remove the errors and try again"); 
     return View(); 
    } 

컨트롤러

[HttpGet] 
    public ActionResult DisplayPic() 
    { 
     ViewBag.Imagepath = "C:\\Users\\Wasfa\\Documents\\Visual Studio 2012\\Projects\\MvcMembership\\MvcMembership\\App_Data\\Uploads\\annonymous.jpg"; 

     return View(); 
    } 

    [HttpPost] 
    public ActionResult DisplayPic(FileManagement fm) 
    { 


     using (var session = DocumentStore.OpenSession("RavenMemberShip")) 
     { 
      string ipath; 
      // string UserName = User.Identity.Name; 
      string UserName = "[email protected]"; 
      var getPath = from p in Session.Query<Registration>() 
          where p.Email == UserName 
          select p; 
      if (getPath.Count() > 0) 
      { 
       foreach (var imgpath in getPath) 
       { 

        ipath = imgpath.Path; 
        ViewBag.Imagepath = ipath; 
       } 

      } 

     } 
     return View(); 
    } 

보기 :

@using (Html.BeginForm()) 

    { 
    <div> 
    <img src="@Url.Content(ViewBag.Imagepath)" width="200" height="200" /> 
    </div> 
    <input type="submit" value="Display" /> 
    } 
+0

http://stackoverflow.com/a/19049374/ 212138 9 – AthibaN

답변

2

내 의견으로는, 당신의 문제는 ASP.NET MVC와 관련이 없지만 일부 HTML/웹 기본 사항이 누락되었습니다.

리소스 (HTML 파일, 이미지 등)에 액세스하려면 HTTP URI 구문을 사용해야한다는 것을 알아야합니다. Windows 파일 시스템 경로 구문을 사용할 수 없으며 사용하지 않아야합니다.

HTML에서 C:\\Users\\Wasfa\\Documents\\Visual Studio 2012\\Projects\\MvcMembership\\MvcMembership\\App_Data\\Uploads\\annonymous.jpg"과 같은 것을 사용하는 것은 완전히 잘못되었습니다. 당신이 당신의 ASP.NET MVC 웹 사이트까지 접근에 그 사용자에 대한 실행이있을 때 상상, 더 잘 이해하기 위해, 그들은 웹 페이지 및 브라우저에 다운로드 한 HTML이 될 것입니다 당신에게 올 것이다 :

<img src="C:\Users\Wasfa\Documents\Visual Studio 2012\Projects\MvcMembership\MvcMembership\App_Data\Uploads\annonymous.jpg" /> 

당신을 수행 그 경로가 컴퓨터에 있다고 생각합니까? 아니.

<img src="http://mywebsite.com/Content/Uploads/annonymous.jpg" /> 

또는 상대처럼 상대 HTTP URI (:

그래서, 서버에서 이미지를 가져 오도록 <img /> 태그를 지시, 당신은 예를 들어, 하나 전체 HTTP URI를 지정해야 웹 사이트의 루트 폴더 경로) : 당신의 접근 방식과

<img src="~/Content/Uploads/annonymous.jpg" /> 

또 다른 문제는 App_Data 특수 폴더와 그 내용은 기본적으로 브라우저에서 액세스 할 수없는 점이다. 따라서 ASP.NET MVC 규칙에 따라 프로젝트에 Content 폴더를 만들어 정적 이미지 및 스타일 셸과 같은 기타 정적 콘텐츠를 보유한 다음 해당 인스턴스에 연결할 수 있습니다.

일단 그렇게하면 아무도 기본 이미지의 상대 경로를 ViewBag 속성으로 제공하지 않게됩니다.

ViewBag.Imagepath = "~/Content/Uploads/annonymous.jpg"; 

그리고 그것은 당신이 원하는 방식으로 사용

<img src="@Url.Content(ViewBag.Imagepath)" width="200" height="200" /> 

가 나는 또한 이후에이 방식을 따라, 데이터베이스에서 가져 오기 경로를 기대합니다.

+0

+1, 좋은 설명이지만 여전히 ViewBag를 사용하는 것은 나쁜 생각입니다. 모델을위한 것입니다! – AthibaN

+0

@Athiban : 네, 동의합니다. 나는 웹 프로그래밍을 처음 접하는 사람들에게 대답을 복잡하게하고 싶지 않았다. 바라기를 그들은 결국 그것을 배울 것이다. – YK1

1
  • 이미지 경로는 슬래시 (/),
  • 이상이어야합니다.이 경로 유형에 대한 자세한 내용은 로컬 시스템에서만 사용할 수 있으며 서버에서는 사용할 수 없습니다.
  • 이미지를 표시하기위한 ViewBag를 사용
  • 는, 이미지 경로를 저장하고

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

편집을 사용하여 모델 속성을 사용하는 것이 나쁜 생각 경로를 가져올 Server.MapPath를 사용해보십시오 :

컨트롤러 :

[HttpGet] 
    public ActionResult DisplayPic() 
    { 
     FileManagement fm = new FileManagement(); 
     fm.Path = "Your image path"; 

     return View(fm); 
    } 

보기 :

`<img src="@Url.Content(Model.path)" alt = "Image" />` 

코드를 확인하지 않았지만,이 작동합니다.

+0

db 경로는 // 슬래시로 저장됩니다. Model.Path가 paticular 사용자의 경로를 얻는 방법을 실제로 얻지 못합니다. 단계별로 설명해 주시겠습니까? 많이 시도했습니다. 감사합니다. – Wasfa

+0

'FileManagement'이 (가) 귀하의 모델입니까? 질문을 모델 정의로 업데이트하십시오. – AthibaN

+0

예, FileManagement가 제 모델입니다. 제 질문을 업데이트했습니다. – Wasfa

0

그것은 당신은 정말 getPath에 대한 하나의 결과이 필요한 것처럼, 이것은 당신이 응용 프로그램을 통해 디버깅 및 imgPath이 무엇인지 볼 수, 코드가 잘 보이는 것을보다

var imgPath= Session.Query<Registration>() 
       .FirstOrDefault(p => p.Email == UserName) 
       .Select(i => i.Path); 

if (!string.IsNullOrEmpty(imgPath) 
    ViewBag.Imagepath = imgPath; 
else 
{ 
    //no user found, handle error 
} 

다른 약간의 코드를 정리할 수 있습니다 보인다 당신의 쿼리가 실행 된 후와 같습니까?

0

수출 할 때 표시 할 이미지가 웹 페이지에서 Excel 인 경우. 이미지의 서버 경로를 사용하십시오. 그렇지 않으면 이미지가 어셈블리 이미지 폴더에서로드되지 않습니다.

:

설정 :

<add key="LogoPath" value="http:\\mysite\\images\\" /> 

코드 :

companyLogo = string.Format("{0}myLogo.png", System.Web.Configuration.WebConfigurationManager.AppSettings["LogoPath"]); 

HTML :

<img src='" + @Url.Content(companyLogo) + "' /> 
+0

이 구성은 작동하지만 몇 가지 더 좋고 바람직한 해결책이 있습니다. 그들 중 하나는 이미 받아 들여진 대답에 있습니다. 웹을 다른 도메인에 배포 할 때 추가 작업이 필요합니다. 프로덕션 환경에서는 바람직한 옵션이 아닙니다. –

+0

필자의 답에서 지적했듯이 상대적인 이미지 경로는 페이지를 엑셀이나 다른 형식으로 내보내는 동안 발견되지 않습니다. – SFK

관련 문제