0% found this document useful (0 votes)
196 views

Create API To Crud Videos Using HTTP Methods and Javascript and Entity Framwork

The document outlines the steps to implement code first migrations in an ASP.NET MVC application using Entity Framework. The steps include: 1. Creating a Video model class and VideoDb context class that inherits from DbContext. 2. Enabling migrations and setting the migrations configuration to auto migrate. 3. Adding seed data and updating the database using migrations. 4. Creating a Videos controller to implement CRUD operations using the VideoDb context. 5. Adding JavaScript/jQuery and Handlebars.js to call the API, manage templates and handle frontend interactions.

Uploaded by

tomeh100
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
196 views

Create API To Crud Videos Using HTTP Methods and Javascript and Entity Framwork

The document outlines the steps to implement code first migrations in an ASP.NET MVC application using Entity Framework. The steps include: 1. Creating a Video model class and VideoDb context class that inherits from DbContext. 2. Enabling migrations and setting the migrations configuration to auto migrate. 3. Adding seed data and updating the database using migrations. 4. Creating a Videos controller to implement CRUD operations using the VideoDb context. 5. Adding JavaScript/jQuery and Handlebars.js to call the API, manage templates and handle frontend interactions.

Uploaded by

tomeh100
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

code first mirgrations steps:

Create Video class in the model folder


-------------------public class Video
{
public virtual Int Id {get;set;}
public virtual string Title {get;set;}
public virtual Int Length {get;set;}
}
Create VideoDb Context Class in the model folder that will inherate from DbCont
ext from the entitly framework
------------------------------public class VideoDb:DbContext
{
public DbSet<Video> Videos {get;set;}
}
enable-migrations form the nuget package console
-----------------------------------------------pm> enable-migrations
this will add a mirgrations folder to solution explor
er
Set auto migrations to true in the migrations folder
---------------------------------------------------turn AutomaticMigrationsEnabled = true;
Update the seed method to insert new row to database such as:
it will check for existing video and it will add or update depending on the vide
o title
------------------------------------------------------------context.Videos.AddOrUpdate(v => v.Title,
new Video(){ Title = "MVC4", Length = 120},
new Video(){ Title = "LINQ", Length = 200}
);
context.SaveChanges();
Update/Add Database from the nuget package console
-----------------------------------------------------------------pm> update-database
Use VideoDb Context in our controller
------------------------------------//Create private db
private VideoDb db;
//initiate new db context in our constractor
public VideosController()
{
db = new VideoDb();
db.Configurations.ProxyCreatingEnable = false;//this if we are working w
ith API
}
implement methods in VideosController
-----------------------------------------//return a collection of Videos from db api/videos
public IEnumerable<Video> GetAllVideos()

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

//Delete method to delete video with id


public HttpResponseMessage DeleteVideo(int id)
{
Video video = db.Videos.Find(id);
if(video == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Videos.remove(video);
try
{
db.SaveChanges();
}
catch(DBUpdateConcurrencyException)
{
return Request.CreateResponse(HttpStatusCide.NotFound);
}
return request.CreateResponse(HttpStatusCode.OK, video);
}
To create our home view we need some javascript library such as "handlebars" and
"jquery"
-----------------------------------------------------------------------------------pm> update-package jquery //this will pick the lastest version
pm> install-package Handlebars.js //Install templating js library Handlebars.js
create our sections script that get rendered at the end of our _Layout.cshtml
----------------------------------------------------------------------@section scripts{
// add handlebars script to our script section (drag and drop option ava
ilable from solution explorer)
<script src="~/Scripts/handlebars.js"/>
//declare javascript video server object/module (private) to do the crud
var videoServer = (function (){
//create video api url that my application will talk to
//such as /api/videos/ using razor syntax
var videoApiUrl = '@Url.RouteUrl("DefaultApi", new{ httproute="",control
ler = "videos"})';
//Add Error Handler alert in case if anything went wrong
$(document).ajaxError(function (event, xhr){
alert(xhr.status + ":" + xhr.statusText);
});
//create function that will return an object of Videos thur jquery ajax
var getVideos = function(){
return $.ajax(videoApiUrl);
};
//function to return video with id
var getVideo = function(id){
return $.ajax(videoApiUrl + "/" + id);
};

//function to update selected video with the server


var updateVideo= function(video){
return $.ajax(videoApiUrl +"/"+ video.Id,{
type: PUT,
data: video
});
};
//function to post video to save to server
var addVideo = function(video){
return $.ajax(videoApiUrl, {
type: "POST",
data: video
});
};
//function to delete video
var deleteVideo = function(id){
return $.ajax(videoApiUrl +"/"+id,{
type: "DELETE"
});
};
//create videoServer return for public interface that point to the priva
te functions
return{
getVideos: getVideos, //videoServer.getVideos is equal to my pri
vate var getVideos
getVideo: getVideo, //videoServer.getVideo,
updateVideo: updatedVideo,
addVideo: addVideo,
deleteVideo: deleteVideo
};
}());//end videoServer function
//create function that will call videoServer methods, process data, upda
te UI
//create module that all methods will be private inside of it
(function(){
//create DOM ready events that will call method refreshVideos
$(function(){
wireEvents();
compileTemplates();
refreshVideos();
});
//get all videos from videoServer.getVideos that return json for
matted object
var refreshVideos = fuction(){
videoServer.getVideos.done(showAllVideos);
};
//Event handler when we click a button edit or save or create/de
lete video
var wireEvents = functions(){
$(document).on("click", ".editVideo", editVideo);

$(document).on("click", "#saveVideo", saveVideo);


$(document).on("click", "#createVideo". createVideo);
$(document).on("click", "#deleteVideo". deleteVideo);
};
//render data to out EditVideo form
var showVideoForEdit = function(video){
var output = templates.videoEdit(video);
$("#videoEditOutput").html(output);
};
//call this method when we click Edit Button
var editVideo = function(){
var id = getId(this);
videoServer.getVideo().done(showVideoForEdit);
};
//Update/add video with server and clear edit form
var saveVideo = function(){
var video ={
"Id": $("#id").val(),
"Title":$("title").val(),
"Length": $("#length").val()
};
var operation;
if(video.Id != "0"){
operation = videoServer.updateVideo(video);
}
else
{
operation = videoServer.addVideo(video);
}
Operation.done(refreshVideos, clearEdit);
return false;
};
// this is to clear the edit display
var clearVideo = function(){
$("#videoEditOutput".empty();
};
//create a video
var createVideo = function(){
var video = {id:0, Title:"", Length:0};
showVideoForEdit(video);
};
//function to get the id of edited video when we click a button
var getId = function(element){
return $(element).parents("tr").attr("data-id");
};
//object to hold my templates display videos template and update
videos template
var templates ={};
//function to add a property to templates object that holds our
compiled template to display
var compileTemplates = function(){
templates.videoTable = Handlebars.compile($("#videoTable

").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>

You might also like