显示ASP.NET MVC的图像列表

时间:2014-07-04 11:38:56

标签: c# asp.net-mvc-4

我有一个接受ID并显示与公司关联的产品图片的应用程序。有2个表,一个用于名为ImagesArchive的旧产品,另一个用于NewImages中的新产品。根据要求,ID只能在NewImages表中有一个产品。所以我能够在我的代码中成功地做到这一点。但是在ImagesArchive表中,由于我正在记录该公司的所有旧产品,因此ID和&之间存在一对多的关系。产品。如何使用iframe和&amp ;;显示列表? MVC GetOld(ID)??什么是捕获错误并显示何时找不到图像的最佳方法,即产品的URL不起作用?

- 图像模型

 public class Images   
       {
           public int ID { get; set; }
           public string URL_FilePath { get; set; }
        }

HTML文件          

   <head>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
       <script type="text/javascript">
           function Imagepreview() {
               var ID = document.getElementById("ID").value;
               document.getElementById("companyImage").src = "api/Images/GetNew/" + ID;
               old();       
           }
           function old() {
               var ID = document.getElementById("KeyID").value;
               document.getElementById("companyOldImage").src = "api/Images/GetOld/" + ID;

           }
       </script>
       <style type="text/css">
           #companyImage {
               width: 181px;
           }
           #archiveImage {
               margin-left: 17px;
           }
       </style>
   </head>
    <body ">
      <div class="jumbotron" align="center">
         <h1>Images API</h1>    
         <p class="lead"></p>        
         <div class="col-md-4" align="center">       
            <input type="text" name="ID" id="ID"/>          
             <input type="button" value="Show Image" onclick="Imagepreview()"/>
             <br>
             <br>
              <iframe src="" id="companyImage" height="200" width="200"> </iframe>
              <iframe src="" id="companyOldImage" height="200" width="200"> </iframe>
         </div>
         <div id="response">
         </div>
      </div>
   </body>
</html>

----------------------控制器获取功能----------

 [System.Web.Mvc.AcceptVerbs("GET")]
        public HttpResponseMessage GetNew(int ID)     
        {
            Images newImages = new Images();
            GetSettingsInfo();
            HttpResponseMessage result = null;

            string sql = "select id,url_filepath from [dbo].[NewImages]  WHERE ID = @ID";
            using (SqlConnection connection = new SqlConnection(ConnectionString))
             {
                using (SqlCommand query = new SqlCommand(sql, connection))
                {
                    SqlDataReader rdr;
                    query.Parameters.Add(new SqlParameter("@ID", ID));
                    query.CommandType = CommandType.Text;
                    connection.Open();
                    query.CommandTimeout = 240;
                    rdr = query.ExecuteReader();
                    if (rdr != null)
                    {
                        while (rdr.Read())
                        {
                            newImages.ID = ConvertFromDBVal<int>(rdr["ID"]);
                            newImages.URL_FilePath = ConvertFromDBVal<string>(rdr["URL_FilePath"]);               
                        }
                    }
                }
            }
         if (newImages.KeyID != 0)
            {
                if (!(newImages.URL_FilePath.Contains("http")))
                    newImages.URL_FilePath = "http://" + newImages.URL_FilePath;
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(newImages.FilePath);           
                HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream stream = httpWebReponse.GetResponseStream();
                Image img = Image.FromStream(stream);
                MemoryStream ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                result = new HttpResponseMessage(HttpStatusCode.OK);
                result.Content = new ByteArrayContent(ms.ToArray());
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
            }
            else
            {
                result = new HttpResponseMessage(HttpStatusCode.NotFound);
            }
                return result;     
        }

 [System.Web.Mvc.AcceptVerbs("GET")]
        public HttpResponseMessage GetOld(int ID)     
        {
            Images newImages = new Images();
  //queries ImagesArchive table instead of ImagesTable
}

1 个答案:

答案 0 :(得分:0)

以下是我使用API​​描述你的方式。您将ID传递给服务并返回服务中图像的2个URL:

public class ImageData
{
   public string OldUrl { get; set; }
   public string NewUrl { get; set; }
}

public class ImageController : ApiController
{
   // Gets 2 images - old and new
   public ImageData GetNew(string id)
   {
      return new ImageData
      {
         OldUrl = "/images/old/" + id,
         NewUrl = "/images/new/" + id,
      };
   }
}

现在定义一些函数以从API检索新URL。这里我有2个函数:1用于执行API检索,1个用于click事件:

/// Gets image URLs from the API

function getImagesFor(idForImage) {
       var imageUrl = $.get('api/Image/GetNew/' + idForImage)
            .done(function(data) {

               // Retrieve 'OldUrl' and 'NewUrl' from the JSON returned

               $("#oldImage").attr('src', data.OldUrl);
               $("#newImage").attr('src', data.NewUrl);
       });
}


// Hooks up the events - 'click' extracts the info and calls the service.
$(document).ready( function() {

   $("#imageButton").click(function() {
      var imageId = $("#imageId").text();
      getImagesFor(imageId);
      return false;
   });
}

并且有一个基本的HTML来查看结果:

<script type="text/javascript">
   <!-- As above -->
</script>

<div>
  <input type="text" id="imageId"/>
  <input type="button"  id="imageButton"/><br/>
  <iframe src="" id="oldImage"/>
  <iframe src="" id="newImage"/>
</div>