2016-03-23 9 views
0

我的實體從數據庫中檢索圖像存儲和使用asp.net網站的API和淘汰賽JS

public class Agent 
    { 
     [Key] 
     [JsonProperty(PropertyName = "agentId")] 
     public int AgentId { get; set; } 
     [JsonProperty(PropertyName = "codeName")] 
     public string CodeName { get; set; } 
     [JsonProperty(PropertyName = "firstName")] 
     public string FirstName { get; set; } 
     [JsonProperty(PropertyName = "lastName")] 
     public string LastName { get; set; } 
     [JsonProperty(PropertyName = "imagePath")] 
     public string ImagePath { get; set; } 
     [JsonProperty(PropertyName = "description")] 
     public string Description { get; set; }   
    } 

我的ViewModel

public class AgentVm 
    { 
     public int AgentId { get; set; } 
     public string CodeName { get; set; } 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public string ImagePath { get; set; } 
     public string Description { get; set; } 
    } 

我獲取網絡API控制器

public IQueryable<AgentVm> GetAgents() 
    { 
     var agents = from b in db.Agents 
      select new AgentVm() 
      { 
       AgentId = b.AgentId, 
       FirstName = b.FirstName, 
       LastName = b.LastName, 
       CodeName = b.CodeName, 
       ImagePath = b.ImagePath 

      }; 
     return agents; 
    } 

我的文章web api控制器

public async Task<HttpResponseMessage> PostAgent(Agent agent) 
{ 
       if (agent != null) 
    { 
     // Extract the image from the image string 
     string regEx = "data:(.+);base64,(.+)"; 
     Match match = Regex.Match(agent.ImagePath, regEx); 

     if (match.Success) 
     { 
      // Get the content-type of the file and the content 
      string imageType = match.Groups[1].Value; 
      string base64image = match.Groups[2].Value; 

      if (imageType != null && base64image != null) 
      { 
       // Verify the content-type is an image 
       string imageRegEx = "image/(.+)"; 
       match = Regex.Match(imageType, imageRegEx); 

       if (match.Success) 
       { 
        // Get the file extension from the content-type 
        string fileExtension = match.Groups[1].Value; 
        // Get the byte-array of the file from the base64 string 
        byte[] image = Convert.FromBase64String(base64image); 

        string path = HttpContext.Current.Server.MapPath("~/images"); 
        string fileName = agent.FirstName + agent.LastName; 

        // Generate a unique name for the file (add an index to it if it already exists)               
        string targetFile = fileName + "." + fileExtension; 
        int index = 0; 
        while (File.Exists(Path.Combine(path, targetFile))) 
        { 
         index++; 
         targetFile = fileName + index + "." + fileExtension; 
        } 

        // Write the image to the target file, and update the agent with the new image path 
        File.WriteAllBytes(Path.Combine(path, targetFile), image); 
        agent.ImagePath = "images/" + targetFile; 

        db.Agents.Add(agent); 
        await db.SaveChangesAsync(); 

        // Create the Location http header 
        var response = Request.CreateResponse(HttpStatusCode.Created, agent); 
        string uri = Url.Link("GetAgent", new { id = agent.AgentId}); 
        response.Headers.Location = new Uri(uri); 

        return response; 
       } 

      } 

     } 
    } 
    throw new HttpResponseException(Request.CreateErrorResponse(
    HttpStatusCode.BadRequest, "Could not deserialize agent")); 
} 

,這是我的js

var ViewModel = function() { 
    var self = this; 
    self.agents = ko.observableArray(); 
    self.error = ko.observable(); 

    self.agent = ko.observableArray(); 
    self.newAgent = { 
     FirstName: ko.observable(), 
     LastName: ko.observable(), 
     CodeName: ko.observable(), 
     Description: ko.observable(), 
     ImagePath: ko.observable() 
    } 

    var agentsUrl = "/api/agents/"; 

    function ajaxHelper(uri, method, data) { 
     self.error(""); // Clear error message 
     return $.ajax({ 
      type: method, 
      url: uri, 
      dataType: "json", 
      contentType: "application/json", 
      data: data ? JSON.stringify(data) : null 
     }).fail(function (jqXHR, textStatus, errorThrown) { 
      self.error(errorThrown); 
     }); 
    } 

    function getAllAgents() { 
     ajaxHelper(agentsUrl, "GET").done(function (data) { 
      self.agents(data); 
     }); 
    } 

    self.addAgent = function (formElement) { 
     var agent = { 
      AgentId: self.newAgent.Agent().AgentId, 
      FirstName: self.newAgent.FirstName(), 
      LastName: self.newAgent.LastName(), 
      CodeName: self.newAgent.CodeName(), 
      Description: self.newAgent.Description(), 
      ImagePath: self.newAgent.ImagePath() 
     }; 

     ajaxHelper(agentsUrl, 'POST', agent).done(function (item) { 
      self.agents.push(item); 
     }); 
    } 

    getAllAgents(); 
}; 

ko.applyBindings(new ViewModel()); 

,這是我的形象元素

<img data-bind="attr:{ src: ImagePath }"/> 

,但圖像不顯示,我想不出來添加上傳, 請人幫助,我不需要角度,只是一個簡單的mvvm,如淘汰賽js,但我是相對新的。

+0

這篇文章對於一個完整的(雖然還不是很小)repro來說相當不錯,但是最後一段很寬泛/不清楚:「*但是圖像沒有顯示,我也不知道添加上傳*」。爲什麼不顯示?你得到了什麼?你有什麼嘗試,調試等? – Jeroen

+0

如何將圖像與淘汰賽綁定 – user2985240

+0

沒有冒犯,但不確定你的評論意味着什麼。 AFAICT你只是重申我已經提到的事情「太廣泛/不清楚」給我...... – Jeroen

回答

0

查看Chrome控制檯生成的<img>元素或firefox中的Firebug(特別是src屬性)。然後將該網址複製到新標籤中,並檢查它是否顯示。我認爲你的問題是元素被正確渲染,但你的項目不能渲染直接圖像,因爲MVC會嘗試使用路由邏輯來查找你請求的控制器/動作,並返回一個HTTP 404. Check this response for a solution

你可以創建一個簡單的表單來上傳文件,或者也可以使用jQuery $ .post,如果你想使用ajax。 Here is a sample for that