显示图像列表.净MVC

本文关键字:MVC 列表 图像 显示图 显示 | 更新日期: 2023-09-27 18:11:22

我有一个应用程序,它接受ID并显示与公司相关的产品图像。这里有两个表,一个是ImagesArchive中的旧产品,另一个是NewImages中的新产品。根据要求,一个ID在NewImages表中只能有一个产品。所以我能够在我的代码中成功地做到这一点。但是在ImagesArchive表中,由于我正在记录该公司的所有旧产品,因此ID &产品。我如何使用iframe &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
}

显示图像列表.净MVC

我想象您是如何使用这个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。这里有两个函数:一个用于API检索,另一个用于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>