Create API To Crud Videos Using HTTP Methods and Javascript and Entity Framwork
Create API To Crud Videos Using HTTP Methods and Javascript and Entity Framwork
{
return db.Videos;
}
//return one video with id from db api/videos/5
public Video GetVideo(int id)
{
var video = db.Videos.Find(id);
if(video == null)
{
throw new HttpResponseException(Request.CreateResponse(httpStatu
sCode.NotFound)); //404 not found
}
return video;
}
//Put method to return the saved video after updated with the db if success othe
rwise return bad request
public HttpResponseMessage PutVideo(int id, Video video)
{
if(ModelState.IsValid && id == video.Id)
{
db.Entry(video).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch(DbUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStateCode.NotFound); /
/return not found
}
return Request.CreateResponse(HttpStateCode.OK, video); //retur
n back video
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest); //retu
rn bad request
}
}
//Post method to add a video to db
public HttpResponseMessage PostVideo(Video video)
{
if(ModelState.IsValid)
{
db.Videos.Add(video);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatus
Code.Created, video);
response.Headers.Location = new Uri(Url.Link("DefaulApi", new{ i
d = video.Id}));
return response;
}
else{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
").html());
templates.videoEdit = Handlebars.compile($("#videoEdit")
.html());
};
//render data to our videoTable template
var showAllVideos = function(data){
var output = templates.videoTable({video:data});
$("#videoTableOutput").html(output);
};
}());
}//end section Scripts
<!-- create a div to place the template that I want to display -->
<div id="videoTableOutput">
</div>
<!-- create a dive to place edit template-->
<div id="videoEditOutput">
</div>
<!-- create a button to create a video
<button id ="createVideo">Create Video</button>
<!-- template to display all videos handlebar.js syntax -->
<script id="videoTable" type="text/html">
<table>
<thead>
<th>Title</th>
<th>Length</th>
<th></th>
</thead>
<tbody>
{{#each video}}
<tr data-id={{Id}}>
<td>{{Title}}</td>
<td>{{Length}}</td>
<td>
<button class="editVideo">Edit</buton>
<button class="deleteVideo">Delete</butt
on>
</td>
</tr>
{{/each}}
</tbody>
</table>
</script>
<!-- template to display edit video event UI -->
<script id="videoEdit" type="text/html">
<hr/>
<form>
<input type="hidden" name="id value="{{Id}}" />
<label for="title">Title:</label>
<input type="text" name="Title" id="title required value
="{{Title}}" />
<label for="lenght">Length</label>
<input type="number" min="0" max="200" name="Length" id=
"length" value="{{Length}}" />
<input type="submit" id="saveVideo" />
</form>
</script>