Click here to Skip to main content
15,121,963 members
Articles / Web Development / ASP.NET
Article
Posted 5 Nov 2013

Stats

210.2K views
13.5K downloads
103 bookmarked

CRUD Operations using Partial View and jQueryUI in ASP.NET MVC4 - Part 2

Rate me:
Please Sign up or sign in to vote.
4.95/5 (82 votes)
11 Jun 2014CPOL5 min read
CRUD Operations using Partial View and jQueryUI in ASP.NET MVC4

Introduction 

This is the second part of the article “CRUD operations using partial views in ASP.NET MVC4”. If you have not visited Part 1, please do so, it would help to understand this part better. In the first part, we have seen how to display training data on the view by making a call to the appropriate action method. The action method uses training repository and repository reads the data from XML file. 

Note: I have tested code using Google Chrome as browser, for other browsers Edit popup may not work pleasantly.   

In this part, we will learn how to do Create, Edit and Delete operations on the training using partial views. We will be using jQueryUI to make the dialog box and calendars. Following is the outline of the complete article:

Part 1 Outline 

  • Overview of Partial View and jQueryUI
  • Creating ASP.NET MVC 4 Application
  • Creating XML File as DB and Training Repository
  • Implement Action method and View

Part 2 Outline

  • Implement Create Operation
  • Implement Edit Operation
  • Implement Delete Operation

Let’s start with Part 2 now. First, we will implement create operation for a training...

Implement Create Operation

  1. Let us create a partial view by right clicking on Shared folder. Give it name as CreatePartialView, make it strongly typed by checking the checkbox for “Create a strongly-typed views” option, select training model and check the checkbox “Create a partial view” option, as shown below:

    Add a Partial View to Project

    CreatePartialView.cshtml file will be added to the Shared folder. Now, we can use this partial view anywhere. Please find the code written in CreatePartialView.cshtml in downloaded code and add similar to those in this file.

  2. In Index.cshtml file, just after the table closing tag, add the following code as shown below:
    JavaScript
    <div id="createForm"></div>
  3. Add appjs folder in Scripts folder and add index.js file under new appjs folder. For selecting the time, will use timepicker. To create timepicker, we have downloaded a plugin to create jQuery timepicker from here. Add downloaded jquery.timepicker.min.js as shown below:

    Adding TimePicker js file

    And add downloaded jquery.timepicker.css to appcss folder under the Content folder as shown below:

    Adding TimePicker css file

  4. Open index.js file and write the following code:
    JavaScript
    var selectedId = 0;
    $(document).ready(function () {
        $(".itemIdClass").hide();
        $("#deleteForm").hide();
    });
    //jQueryUI method to create dialog box
    $("#createForm").dialog({
        autoOpen: false,
        modal: true,
        width: 450,
        title: "Create Training"
    });

    Here selectedId is a variable that is initially assigned to zero.
    $(".itemIdClass").hide();: This code will hide TrainingId column from table.
    $("#createForm").dialog();: dialog() is a jQueryUI method that will create a dialog box to show the Create Training form.

  5. On Create training partial view, we want to show instructor list as dropdown to select a instructor. For this, we have written the following code in CreatePartialView.cshtml file to bind instructor list to the select tag.
    JavaScript
    <select id="selectInstructor">
        <option selected="selected">Select Instructor </option>
    </select>
  6. Add create.partialview.js under the appjs folder and write the following code in create.partialview.js file. Do not forget to give the reference for create.partialview.js on CreatePartialView.cshtml file.
    JavaScript
    $(document).ready(function () {
           //Create jQuery timpicker
            $("#timepicker").timepicker();
               //Create jQueryUI datepicker
               $("#startdatepicker").datepicker();
               //Create jQueryUI datepicker
               $("#enddatepicker").datepicker();
               
               $.ajax({
                //Call GetInstructorList action method
                url: "/Home/GetInstructorList",
                type: 'Get',
                success: function (data) {
                    $.each(data, function (i, value) {
                        $('#selectInstructor').append
                        ($('<option>').text(value).attr('value', value));
                    });
                }
            });
        });
  7. In HomeController, write the following code:
    JavaScript
    [HttpGet]
    public JsonResult GetInstructorList()
    {
        var allInstructors = _trainingRepository.GetInstructor().ToList();
        return Json(allInstructors, JsonRequestBehavior.AllowGet);
    }

    [HttpGet] is an attribute used to get the data. GetInstructorList method returns Instructors list as json form.

  8. In index.js, use jQuery Ajax method to call CreatePartialView() action method.
    JavaScript
    $("#buttonCreate").button().click(function () {
        $.ajax({
           //Call CreatePartialView action method
           
            url: "/Home/CreatePartialView",
            type: 'Get',
               success: function (data) {        
                $("#createForm").dialog("open");
                $("#createForm").empty().append(data);
                $("#editForm").hide();
            },
            error: function () {
                alert("something seems wrong");
            }
        });
    });
  9. Inside the HomeController, add the following code as shown below:
    JavaScript
    [HttpGet]
    public ActionResult CreatePartialView()
    {
        return PartialView("CreatePartialView");
    }            

    CreatePartialView is an Action method whenever it will be called will return CreatePartialView.cshtml file.

  10. When you click on Create new Training Button, Create Training form will open as a dialog box as shown below:

    Create Training Popup

  11. Submit button is not working now, so let us implement the functionality to create a new training. Open create.partialview.js file and write the following code to send new training to the server.
    JavaScript
    $("#submit-button").click(function () {
        // On submit button click close dialog box
        $("#createForm").dialog("close");
        
        //Set inserted values
        var name = $("#trainingname").val();
        var selectInstructor = $("#selectInstructor").val();
        var startdatepicker = $("#startdatepicker").val();
        var enddatepicker = $("#enddatepicker").val();
        var timepicker = $("#timepicker").val();
        var duration = $("#duration").val();
        
        // Call Create action method
        $.post('/Home/Create', { "name": name, 
        "instructor": selectInstructor, "startdate": startdatepicker, 
                                 "enddate": enddatepicker, 
                                 "time": timepicker, "duration": duration },
            function () {
                alert("data is posted successfully");
                window.location.reload(true);
                
             });
    });            
  12. In HomeController, write the following code to call InsertTraining() method of repository to save data in an XML file.
    JavaScript
    [HttpPost]
    public void Create(Training training)
    {
        _trainingRepository.InsertTraining(training);
    }            

    [HttpPost] is an attribute used to post the data. Create method accepts the newly created training object. Then call InsertTraining() method is implemented in TrainingRepository.cs file.

  13. Run the application, click on “Create new Training” button, a dialog box will open.
  14. In “Create Training” popup, fill the form and when you click on submit button, data will be saved finally in Trainings.xml file. As of now, there is no validation logic for the given value.

Implement Edit Operation

  1. Add a Partial View named as EditPartialView.cshtml to Shared folder to make it strongly-typed.
  2. Write the same code as written in downloaded EditPartialView.cshtml file.
  3. Add the following tag just after the createForm div tag:
    JavaScript
    <div id="editForm"></div>
  4. Add the following code in index.js file to create dialog box to show edit training form:
    JavaScript
    //jQueryUI method to create dialog box
           $("#editForm").dialog({
               autoOpen: false,
               modal: true,
               width: 450,
               title: "Edit Selected Training"
           });
    
  5. Add edit.partialview.js under the appjs folder and write the following code in edit.partialview.js file. Do not forget to give the reference for edit.partialview.js on EditPartialView.cshtml file.
    JavaScript
    $(document).ready(function () {
        //Create jQuery timpicker
        $("#edittimepicker").timepicker();
          //Create jQueryUI datepicker
            $("#startdatepicker").datepicker();
            $("#enddatepicker").datepicker();
            $.ajax({
                url: "/Home/GetInstructorList",
                type: 'Get',
                success: function (data) {
                    $.each(data, function (i, value) {
                        ('#editselectInstructor').append($
                        ('<option>').text(value).attr('value', value));
                    });
                }
            });
        });
        
        $("#update-button").click(function () {
            $("#editForm").dialog("close");
            
            var id = $("#traininId").val();
            var name = $("#name").val();
            var instructor = $("#editselectInstructor").val();
            var startdatepicker = $("#startdatepicker").val();
            var enddatepicker = $("#enddatepicker").val();
            var timepicker = $("#edittimepicker").val();
            var duration = $("#duration").val();
         // Call Edit action method
            $.post('/Home/Edit', { "id": id, "name": name, 
            "instructor": instructor, "startdate": startdatepicker, 
                                    "enddate": enddatepicker, 
                                    "time": timepicker, 
                                    "duration": duration }, function () {
                alert("data is posted successfully");
                window.location.reload(true);
            });
        });            
  6. In HomeController, write the following code:
    JavaScript
    [HttpGet]
        public ActionResult EditPartialView(string id)
        {
            int selectedTrainingId = Convert.ToInt32(id);
            Training selectedTraining = _trainingRepository.GetTrainingByID(selectedTrainingId);
            
            return PartialView("EditPartialView", selectedTraining);
        }
        
    [HttpPost]
        public void Edit(Training training)
        {
            _trainingRepository.EditTraining(training);
        }
  7. Run the application, click on Edit button Edit Training dialog box will open as shown below:

    Edit Training Popup

  8. Edit the training, when you click on Update button, updated data will be saved in Trainings.xml file.

Implement Delete Operation

  1. Let us implement functionality to delete training. When we click on Delete button, we want to show confirmation dialog box. To do that, first write the following code in Index.cshtml file:
    JavaScript
    <div id="deleteForm">
        <p>Please provide the confirmation to delete this training.</p>
        <input type="button" value="Yes" class="okDelete btnStyle" />
    </div>            
  2. Add the following code in index.js file to create dialog box to show edit training form:
    JavaScript
    //jQueryUI method to create dialog box
    $("#deleteForm").dialog({
        autoOpen: false,
        modal: true,
        title: "Delete Selected Training"
    });            
  3. Write jQuery click function, this function will be called when Delete button will be clicked:
    JavaScript
    $(".buttonDelete").button().click(function () {
        //Open the dialog box
        $("#deleteForm").dialog("open");
        //Get the TrainingId
        selectedId = $(this).parents('tr:first').children
        ('td:first').children('input:first').attr('value');
    });            
  4. Click on Delete button. Hope you will get the similar screen as shown below:

    Delete Training Popup

Conclusion

The above article provided a walkthrough to create “CRUD operations using partial views in ASP.NET MVC4”. Hope it would be helpful to understand how to make AJAX calls, use Partial Views and jQueryUI. If you face any problem while following the steps given in the article, please refer to the downloaded code. In case of any query, feel free to comment here. Thanks.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Snesh Prajapati
Software Developer
India India
I am a Software Developer working on Microsoft technologies. My interest is exploring and sharing the awesomeness of emerging technologies.

Comments and Discussions

 
AnswerRe: Master -Detail Crud operation Pin
Snesh Prajapati7-Aug-14 19:05
professionalSnesh Prajapati7-Aug-14 19:05 
GeneralGreat Article. My Vote 5 Pin
AnandKumar R25-Jul-14 2:20
MemberAnandKumar R25-Jul-14 2:20 
AnswerRe: Great Article. My Vote 5 Pin
Snesh Prajapati25-Jul-14 4:04
professionalSnesh Prajapati25-Jul-14 4:04 
QuestionExcellent Pin
stephen selvaraj11-Jul-14 5:16
Memberstephen selvaraj11-Jul-14 5:16 
AnswerRe: Excellent Pin
Snesh Prajapati11-Jul-14 18:23
professionalSnesh Prajapati11-Jul-14 18:23 
GeneralExcellent Article Pin
Vanmala1-Jul-14 4:32
MemberVanmala1-Jul-14 4:32 
AnswerRe: Excellent Article Pin
Snesh Prajapati1-Jul-14 6:29
professionalSnesh Prajapati1-Jul-14 6:29 
QuestionLove this article, esp. use of Javascript Pin
SilverSmithSyr20-Jun-14 6:29
MemberSilverSmithSyr20-Jun-14 6:29 
Love the examples of how to use Javascript with ASP.net. Simple and easy to follow
AnswerRe: Love this article, esp. use of Javascript Pin
Snesh Prajapati20-Jun-14 7:12
professionalSnesh Prajapati20-Jun-14 7:12 
GeneralVery Nice Tutorial Pin
Musthaan13-Jun-14 4:38
MemberMusthaan13-Jun-14 4:38 
AnswerRe: Very Nice Tutorial Pin
Snesh Prajapati13-Jun-14 6:03
professionalSnesh Prajapati13-Jun-14 6:03 
QuestionGreat tutorial Pin
Member 1001270711-Jun-14 17:18
MemberMember 1001270711-Jun-14 17:18 
AnswerRe: Great tutorial Pin
Snesh Prajapati11-Jun-14 17:56
professionalSnesh Prajapati11-Jun-14 17:56 
GeneralAwesome Article mam Pin
Coder Abhinav Kumar Singh1-May-14 0:51
professionalCoder Abhinav Kumar Singh1-May-14 0:51 
AnswerRe: Awesome Article mam Pin
Snesh Prajapati1-May-14 2:34
professionalSnesh Prajapati1-May-14 2:34 
QuestionGood Article Pin
ankur_06032-Apr-14 21:36
Memberankur_06032-Apr-14 21:36 
AnswerRe: Good Article Pin
Snesh Prajapati2-Apr-14 21:42
professionalSnesh Prajapati2-Apr-14 21:42 
Questionsimple example of jqueryu dialog and asp.net mvc Pin
Rohit Kesharwani10-Feb-14 8:59
MemberRohit Kesharwani10-Feb-14 8:59 
AnswerRe: simple example of jqueryu dialog and asp.net mvc Pin
Snesh Prajapati10-Feb-14 16:49
professionalSnesh Prajapati10-Feb-14 16:49 
Suggestionsame post as you define Pin
kiritg10-Feb-14 2:43
Memberkiritg10-Feb-14 2:43 
AnswerRe: same post as you define Pin
Snesh Prajapati10-Feb-14 2:57
professionalSnesh Prajapati10-Feb-14 2:57 
GeneralRegarding the tutorial Pin
jitendra prajapat27-Jan-14 4:39
Memberjitendra prajapat27-Jan-14 4:39 
AnswerRe: Regarding the tutorial Pin
Snesh Prajapati27-Jan-14 6:25
professionalSnesh Prajapati27-Jan-14 6:25 
QuestionThanks note + Request Pin
darpan pathak22-Jan-14 20:44
Memberdarpan pathak22-Jan-14 20:44 
QuestionVote Pin
santosh panchal13-Jan-14 0:57
Membersantosh panchal13-Jan-14 0:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.