• How to Save the Data Submitted into SQL Database

    by  • January 11, 2016 • Microsoft ADO.NET, Microsoft ASP.NET MVC, Microsoft SQL Server • 0 Comments

    Here we will discuss, how can we save the data submitted by the user into a database. We don’t directly interact with the database. For database interaction, we have to add ADO.NET entity framework data model as we did in the previous article. After adding the ADO.NET entity framework data model, we write a two methods in our controller class to ‘GET’ the HTTP request and to’POST’ the HTTP request. As shown Below;

    When the user submits a form, the HTTP Post AddBook() is called. We add a attribute [ValidateAntiForgeryToken] which is used to prevent the forgery of the request. We must declare this attribute with HTTP Post request method. In the AddBook() method, we first see if the model is in valid state, means it is according to the validation attributes that we have added in the model class. Then we make an object of the database ‘store’ and add book’s detail in our database by dc.Books.Add(newBook).  Then we save the changes that we a save the changes we have made in our database by dc.SaveChange() method. Then we clear the form by ModelState.Clear() method. When data successfully added in our database, we display a message “Successfully added a new book”.

    Now look at the AddBook.cshtml View where we make a form to be filled by the user.

    In the above View, we use AntiforgeryToken method to prevent forgery of HTTP request and ValidateSummary() method to check the validation of form. Now when the user submits the form, the data submitted is saved in the SQL database. The output is shown below;

    IndexViewFillingForm NewBookAddeddatabase


    Best WordPress Themes and Plugins with Great Team and Support!

    Leave a Reply