0

my entity

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; }        
    }

my 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; }
    }

my Get web api controller

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;
    }

my post web api controller

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"));
}

and this is my 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());

and this is my image element

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

but the image is not displaying and i can't figure out to add an upload, please someone help , i don't need angular , just a simple mvvm such as knockout js but am relative new in it.

3
  • The post starts off quite okay with a full (though not yet quite minimal) repro, but then the final paragraph is broad/unclear: "but the image is not displaying and i can't figure out to add an upload". Why is it not displaying? What do you get? What have you tried, debugged, etc? Commented Mar 23, 2016 at 6:10
  • how do bind the image with knockout Commented Mar 23, 2016 at 6:55
  • No offense, but not sure what you meant with that comment. AFAICT you're just restating the thing I already mentioned was "too broad/unclear" to me... Commented Mar 23, 2016 at 7:54

1 Answer 1

0

Look at the generated <img> element with Chrome console, or Firebug from firefox (specially the src property). Then copy the URL in a new tab and check if its displayed. I think your problem is that the element is rendered correctly, but your project cannot render direct images, as MVC will try to use the route logic to find the controller/action you are requesting, returning an HTTP 404. Check this response for a solution

You can create a simple form to upload files, or perhaps you can use jquery $.post, if you want to use ajax. Here is a sample for that

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.