ASP.NET MVC 5 Tutorial :: Updating Data With Entity Framework

ASP.NET MVC 5 contains a number of improvements over previous versions, including some new features, improved user experiences; native support for JavaScript libraries to build multi-platform CSS and HTML5 enabled sites and better tooling support.You’re going to learn how to use partial views in ASP.NET MVC (for promoting re-usability) and how to update data using the Entity Framework.

In this article, you’re going to learn how to use partial views in ASP.NET MVC (for promoting re-usability) and how to update data using the Entity Framework.hflnet52

Similar to the last section, we’re going to implement this feature in two steps. First, we’re going to add a link in front of each video that would take us to a page populated with the video details. Next, we’ll implement updating the video in the database.

Step 1: Creating a Page Populated with Video Details

In this step, we’re going to add an edit link in front of each video. The link should take us to a URL like /videos/edit/{id} where {id} is the ID of the video.

Open up Index view inside Views > Videos and change the <li> as follows:

Again, here we’re using the ActionLink helper method you saw in the last step. The first argument is the label for the link, the second argument is the target action, and the third argument is an anonymous object used to supply additional parameters to the route. In this case, we’re passing the ID of each video. With this, ActionLink will return markup like:

When the user clicks on this link, we need to take them to a page with a form populated with the video details. We need an action to handle this request. Inside this action, we’re going to fetch the video with the given ID from the database, and put it on the view. Create a new action in the VideosController as follows:

In the first line, we’re using our DbSet (_dbContext.Videos) but this time, instead of using the ToList method (to get all videos), we use SingleOrDefault. Both of these methods are LINQ extension methods. With this method, we get a single object from the database. Default means that if no object matching the criteria is found, null is returned. Note that the argument to this method is a lambda expression that specifies the criteria.

If the video is not found, we call the HttpNotFound method and return its value.

This method returns HttpNotFoundResult which is yet another ActionResult.With this line, the user will automatically be redirected to a standard “Page Not Found” page in your application.

Finally, if the video is found, we return a view and populate it with the video object:

Now, let’s go ahead and create this view. Inside the Views folder, right-clickVideos and go to Add > View… Set the name of this view to Edit and ensure that the layout is selected.

We want to display a form to edit a video. This form looks identical to the form we created earlier for adding a video. Following the DRY principle (Don’t Repeat Yourself) of software engineering, let’s refactor our existing code and prevent code duplication.

Right-click the Videos folder again, and go to Add > View… Set the name of this view to _VideoForm (note the underscore) and make sure to tick Create as a partial view.image12

When you tick this option, the layout checkbox becomes disabled. A partial view is like a small view that we can reuse in many views. It doesn’t have a layout, so it’s not a full view. In this case, we’re going to extract our video form and put it in this partial view so we can reuse it in both the add and edit views.

Open up New.cshtml. Select all the markup inside the using block (excluding the using block), and then cut and paste it into _VideoForm.cshtml. This is the markup you need to move to the partial view:

Make sure to set the model for this partial view at the top of the view:

Back to New.cshtml, change the using block as follows:

Here we’re using RenderPartial helper method to include the markup in another view, in this case _VideoForm. Note that by convention, partials are prefixed with an underscore.

Also, note that the call to RenderPartial is terminated by a semicolon because unlike the other helper methods you’ve seen so far (e.g., Html.LabelFor, Html.TextBoxFor), this method directly writes markup to the response, whereas the other helper methods return an MvcHtmlString which is then converted to a string by the view engine.

Now we’re going to reuse this partial view in our Edit Video page. Copy the entire using block in New.cshtml and paste it into Edit.cshtml. Then change the action name from Add to Update. Your Edit.cshtml should look like this:

Run the application with Ctrl+F5. You’ll see a runtime error because Visual Studio redirects you to /videos/edit without specifying the ID of the video to edit. Change the address in the browser and navigate to /videos to see the list of videos. Click the edit link in front of one of the videos. You’ll be redirected to the edit form populated with the video you selected.

In the next step, we’re going to save the changes to the database.

Step 2: Updating a Video in the Database

In the last step, when we created our Edit view, we set the target action to Update.In this step, we need to implement this action to update the video. Add a new action to VideosController as follows:

The code should be very familiar, except for a few minor differences.

First, I’ve decorated this action with the [HttpPost] attribute. This tells the MVC runtime that this action can only be called when there is an HTTP POST request.

Note that I named this variable videoInDb to distinguish it from the video object passed as a result of posting the form.

Next, we check to see if the video was found or not, just like before
to update the database.

Then we update the Title, Description and Genre properties of videoInDb and call _dbContext.SaveChanges() to update the database.

DbContext will issue an UPDATE SQL statement based on the properties we have updated. Finally, we redirect the user to the list of videos.

Let’s run the application and see if everything is working. Navigate to /videos, andclick the Edit in front of the first video. Make some changes, and click the Save button. You’ll be redirected to the 404 Not Found page. Why is that? This is one of those issues that you may encounter when you forget to add a hidden field in your form. Let’s go back to our action and see why exactly this happened:

If you run the application in the debug mode and put a breakpoint here, you’ll see that the value of video.Id is 0. Thus, the request that is sent to the server does not have a value for the ID of the video. It only includes values for Title, Descriptionand Genre, which come from the input fields on the form. To send the value of Video.ID, we need to add a hidden field.

Open up _VideoForm.cshtml and add a hidden field before the Save button:

You can add this hidden field anywhere here, but my personal convention is to add them before the submit button. This way, I always know where to look when I’m looking for hidden fields.

Run the application again, try to edit a video, make a few changes, and save. Everything should work.

Best ASP.NET MVC 5 Hosting Recommendation

ASPHostPortal.com

ASPHostPortal.com is Perfect, they have a suitable hosting plan for a starter inDotNetNuke Hosting. ASPHostPortal is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.

HostForLIFE.eu

HostForLIFE.eu guarantees 99.9% uptime for their professional DotNetNuke hostingand actually implements the guarantee in practice. HostForLIFE.eu is the service are excellent and the features of the web hosting plan are even greater than many hosting. HostForLIFE.eu offer IT professionals more advanced features and the latest technology. Relibility, Stability and Performance of  servers remain and TOP priority. Even basic service plans are equipped with standard service level agreements for 99.99% uptime. Advanced options raise the bar to 99.99%. HostForLIFE.eu revolutionized hosting with Plesk Control Panel, a Web-based interface that provides customers with 24×7 access to their server and site configuration tools.