Part of the operator profile I need to add the operator image.
I add an image ID (key) Field to the modal.
1: namespace MvcApplication1.Models
2: {
3: public class Operator
4: {
5: public Operator()
6: {
7:
8: }
9: [Key]
10: public int Id { get; set; }
11:
12: private string mName;
13:
14: public string Name
15: {
16: get { return mName; }
17: set { mName = value; }
18: }
19:
20: private string mOperatorImage;
21:
22: public string OperatorImage
23: {
24: get { return mOperatorImage; }
25: set { mOperatorImage = value; }
26: }
27: }
28: }
Change the cshtml view to display the Operator Image
1: <body id="body" >
2: <div class="main-content">
3: <div>
4: <h1>All Operators</h1>
5: <ul id="OperatorsList"/>
6: </div>
7: <div>
8: <input type="button" id="CallWebApi" value="Call web api" />
9: <p id="product" />
10: <img src="http://localhost:20385/api/Images/5"//>
11: </div>
12: </div>
13: <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
14: <script>
15:
16: $(document).ready(function () {
17:
18: $("#CallWebApi").on("click", function (event) {
19: // Send an AJAX request
20: $.getJSON("api/OperatorData/",
21: function (data) {
22: // On success, 'data' contains a list of products.
23: $.each(data, function (key, val) {
24:
25: var theOperatorName = val.Name ;
26:
27: var theOperatorImage = val.OperatorImage;
28:
29: $('<img/>', { src: "http://localhost:20385/api/Images/" + theOperatorImage }).
30: appendTo($('#OperatorsList'));
31:
32: // Add a route for the routes list.
33: $('<li/>', { text: theOperatorName })
34: .appendTo($('#OperatorsList'));
35: });
36: });
37: });
38: });
39:
40: </script>
41: </body>
In order to retrieve the image we are posting a request to ImagesController.
Add the Images controller :
1:
2: namespace MvcApplication1.Controllers
3: {
4: public class ImagesController : ApiController
5: {
6: public ImagesController()
7: {
8:
9: }
10:
11: // GET api/Images/5
12: public HttpResponseMessage Get(string id)
13: {
14: HttpResponseMessage response = new HttpResponseMessage();
15:
16: var Fs = new FileStream(@"C:\temp\zvika.png", FileMode.Open);
17:
18: Image img = Image.FromStream(Fs);
19: Fs.Close();
20: Fs.Dispose();
21:
22: MemoryStream ms = new MemoryStream();
23: img.Save(ms, ImageFormat.Png);
24:
25:
26: response.Content = new ByteArrayContent(ms.ToArray());
27: ms.Close();
28: ms.Dispose();
29:
30: response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
31: response.StatusCode = HttpStatusCode.OK;
32:
33: return response;
34: }
35: }
36: }
and walla
Resources
http://www.dotnetcurry.com/ShowArticle.aspx?ID=856