Home > DeveloperSection > Articles > CRUD Operation Using Modal Dialog in ASP.NET MVC

CRUD Operation Using Modal Dialog in ASP.NET MVC


ASP.NET MVC ASP.NET MVC 
Ratings:
52 Comment(s)
 127572  View(s)
Rate this:

CRUD Operation Using Modal Dialog in ASP.NET MVC


In this article I am going to explain how to add, edit, delete and find [CRUD (Create, Retrieve, Update, Delete)] records using razor view engine in ASP.NET MVC3 or above version. It will display modal dialog if the JavaScript is turned on otherwise a simple view page, when we try to add and edit the records of student.

Please follow the steps given below to create an application that allows user to add, edit, delete and find records of student.

Open Microsoft Visual Studio 2010 à Select New Project à Select Web from the Installed Templates à Select ASP.NET MVC3 or MVC4 Web Application à Enter the project name Modal_CRUD_MVC in the Name textbox à Click OK.

CRUD operation using Modal dialog in ASP.NET MVC

After select the project you can see the following dialog box:

Select Empty from the Select a template option à Select Razor view engine à Click OK.CRUD operation using Modal dialog in ASP.NET MVC

Add the following Modal classes (Student and StudentContext) in your Model folder:

Student class represents the table structure in the database and StudentContext Students property represents the name of table and data of the students in the database.

    public class Student

    {

        public int StudentID {  get;  set; }

        public string Name { get; set; }

        public string Age { get; set; }

        public string State { get; set; }

        public string Country { get; set; }

    }

    public class StudentContext : DbContext

    {

        public DbSet<Student> Students

        {

            get;

            set;

        }

    }

 

Also include Entity framework reference in your project because in this application we are going to use entity framework code first model to add, edit, delete and find records from the database. To include entity framework dll, follow these steps:

Go to Project à Manage NuGet Packages à Enter entity framework in the search textbox and search online.

CRUD operation using Modal dialog in ASP.NET MVC

You will find latest version of Entity framework version.

You also have to configure your web.config file for the implementation of this project. Add the connectionStrings element under configuration tag:

  <connectionStrings>

    <add name="StudentContext"connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=StudentDb;Integrated Security=true;"providerName="System.Data.SqlClient" />

  </connectionStrings>

 

Add a Controller in your project and edit the controller name as HomeController as shown in the figure below:

CRUD operation using Modal dialog in ASP.NET MVC

After adding HomeController, add an Index view into your project:CRUD operation using Modal dialog in ASP.NET MVC

Edit the Index view and add the following code as given below. Also include these files (jquery-ui.min.css, jquery-1.7.1.min.js, jquery-ui-1.8.20.min.js) in your project.

@model IEnumerable<Modal_CRUD_MVC.Models.Student>

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

    <link href="@Url.Content("~/Content/themes/base/minified/jquery-ui.min.css")" rel="stylesheet" type="text/css" />

    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>

    <script type="text/javascript">

        $(document).ready(function () {

 

            $.ajaxSetup({ cache: false });

           

            $("#openDialog").live("click", function (e) {

                e.preventDefault();

                var url = $(this).attr('href');

 

                $("#dialog-edit").dialog({

                    title: 'Add Student',

                    autoOpen: false,

                    resizable: false,

                    height: 355,

                    width: 400,

                    show: { effect: 'drop', direction: "up" },

                    modal: true,

                    draggable: true,

                    open: function (event, ui) {

                        $(this).load(url);

                    },

                    close: function (event, ui) {

                        $(this).dialog('close');

                    }

                });

 

                $("#dialog-edit").dialog('open');

                return false;

            });

 

            $(".editDialog").live("click", function (e) {

                var url = $(this).attr('href');

                $("#dialog-edit").dialog({

                    title: 'Edit Customer',

                    autoOpen: false,

                    resizable: false,

                    height: 355,

                    width: 400,

                    show: { effect: 'drop', direction: "up" },

                    modal: true,

                    draggable: true,

                    open: function (event, ui) {

                        $(this).load(url);

 

                    },

                    close: function (event, ui) {

                        $(this).dialog('close');

                    }

                });

 

                $("#dialog-edit").dialog('open');

                return false;

            });

 

            $(".confirmDialog").live("click", function (e) {

 

                var url = $(this).attr('href');

                $("#dialog-confirm").dialog({

                    autoOpen: false,

                    resizable: false,

                    height: 170,

                    width: 350,

                    show: { effect: 'drop', direction: "up" },

                    modal: true,

                    draggable: true,

                    buttons: {

                        "OK": function () {

                            $(this).dialog("close");

                            window.location = url;

 

                        },

                        "Cancel": function () {

                            $(this).dialog("close");

 

                        }

                    }

                });

                $("#dialog-confirm").dialog('open');

                return false;

            });

 

            $(".viewDialog").live("click", function (e) {

                var url = $(this).attr('href');

                $("#dialog-view").dialog({

                    title: 'View Customer',

                    autoOpen: false,

                    resizable: false,

                    height: 355,

                    width: 400,

                    show: { effect: 'drop', direction: "up" },

                    modal: true,

                    draggable: true,

                    open: function (event, ui) {

                        $(this).load(url);

 

                    },

                    buttons: {

                        "Close": function () {

                            $(this).dialog("close");

 

                        }

                    },

                    close: function (event, ui) {

                        $(this).dialog('close');

                    }

                });

 

                $("#dialog-view").dialog('open');

                return false;

            });

 

            $("#btncancel").live("click", function (e) {

                $("#dialog-edit").dialog('close');

 

            });

        });  

    </script>

</head>

<body>

    <table align="center" width="800px">

        <tr>

            <td>

                @Html.ActionLink("Create New", "AddEditRecord", "Home", null, new { @id = "openDialog" })

            </td>

        </tr>

    </table>

    <table cellpadding="10" style="border: 1px solid black; font-family: Verdana;" align="center"

        width="800px">

        <tr>

            <th>

                @Html.DisplayNameFor(model => model.Name)

            </th>

            <th>

                @Html.DisplayNameFor(model => model.Age)

            </th>

            <th>

                @Html.DisplayNameFor(model => model.State)

            </th>

            <th>

                @Html.DisplayNameFor(model => model.Country)

            </th>

            <th>

            </th>

        </tr>

        @foreach (var item in Model)

        {

            <tr>

                <td align="center">

                    @Html.DisplayFor(modelItem => item.Name)

                </td>

                <td align="center">

                    @Html.DisplayFor(modelItem => item.Age)

                </td>

                <td align="center">

                    @Html.DisplayFor(modelItem => item.State)

                </td>

                <td align="center">

                    @Html.DisplayFor(modelItem => item.Country)

                </td>

                <td>

                    @Html.ActionLink("Edit", "AddEditRecord", new { id = item.StudentID }, new { @class = "editDialog" })|

                    @Html.ActionLink("Details", "Details", new { id = item.StudentID }, new { @class = "viewDialog" }) |

                    @Html.ActionLink("Delete", "DeleteRecord", new { id = item.StudentID }, new { @class = "confirmDialog" })

                </td>

            </tr>

        }

    </table>

    <div id="dialog-confirm" style="display: none">

        <p>

            <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>

            Are you sure to delete ?

        </p>

    </div>

    <div id="dialog-edit" style="display: none">

    </div>

    <div id="dialog-view" style="display: none">

    </div>

</body>

</html>

 

I have put all the code necessary to perform add, edit, delete and find records of the students in the Index view. In this project we do not have any Layout or Master page.

After including files in the project, your solution explorer might something look like this:CRUD operation using Modal dialog in ASP.NET MVC

Add a partial view _StudentData in Views à Home folder.CRUD operation using Modal dialog in ASP.NET MVC

Edit the _StudentData partial view as below:

@model Modal_CRUD_MVC.Models.Student

@using (Ajax.BeginForm("AddEditRecord", "Home", new AjaxOptions{ HttpMethod = "POST", UpdateTargetId = "studentDialog" }))

{

    @Html.ValidationSummary(true)

 

    <fieldset>

        <legend>Student</legend>

        @if (ViewBag.IsUpdate == true)

        {

            @Html.HiddenFor(model => model.StudentID)

        }

        <div class="editor-label">

            @Html.LabelFor(model => model.Name)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Name)

            @Html.ValidationMessageFor(model => model.Name)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Age)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Age)

            @Html.ValidationMessageFor(model => model.Age)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.State)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.State)

            @Html.ValidationMessageFor(model => model.State)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Country)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Country)

            @Html.ValidationMessageFor(model => model.Country)

        </div>

        <p>

            @if (ViewBag.IsUpdate == true)

            {

                <input type="submit" value="Update" id="btnUpdate" name="cmd" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

            }

            else

            {

                <input type="submit" value="Save" id="btnSave" name="cmd" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

            }

            <input type="button" value="Cancel" id="btncancel" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

        </p>

    </fieldset>

}

 

Also add StudentData view in the same folder Views à Home. This view will response by the controller to the browser if the JavaScript is turned off otherwise the above partial view will display in a modal dialog to the user.

@model Modal_CRUD_MVC.Models.Student

@using (Html.BeginForm("AddEditRecord", "Home"))

{

    @Html.ValidationSummary(true)

 

    <fieldset>

        <legend>Student</legend>

        @if (ViewBag.IsUpdate == true)

        {

            @Html.HiddenFor(model => model.StudentID)

        }

        <div class="editor-label">

            @Html.LabelFor(model => model.Name)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Name)

            @Html.ValidationMessageFor(model => model.Name)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Age)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Age)

            @Html.ValidationMessageFor(model => model.Age)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.State)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.State)

            @Html.ValidationMessageFor(model => model.State)

        </div>

        <div class="editor-label">

            @Html.LabelFor(model => model.Country)

        </div>

        <div class="editor-field">

            @Html.EditorFor(model => model.Country)

            @Html.ValidationMessageFor(model => model.Country)

        </div>

        <p>

            @if (ViewBag.IsUpdate == true)

            {

                <input type="submit" value="Update" id="btnUpdate" name="cmd" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

            }

            else

            {

                <input type="submit" value="Save" id="btnSave" name="cmd" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />

            }

            @Html.ActionLink("Back to List", "Index")

        </p>

    </fieldset>

}

 

Add a partial view _StudentDetails in Views à Home folder.

Edit the _StudentDetails partial view as below:

@model Modal_CRUD_MVC.Models.Student

 

<fieldset>

    <legend>Student</legend>

 

    <div class="display-label">

         @Html.DisplayNameFor(model => model.Name)

    </div>

    <div class="display-field">

        @Html.DisplayFor(model => model.Name)

    </div>

 

    <div class="display-label">

         @Html.DisplayNameFor(model => model.Age)

    </div>

    <div class="display-field">

        @Html.DisplayFor(model => model.Age)

    </div>

 

    <div class="display-label">

         @Html.DisplayNameFor(model => model.State)

    </div>

    <div class="display-field">

        @Html.DisplayFor(model => model.State)

    </div>

 

    <div class="display-label">

         @Html.DisplayNameFor(model => model.Country)

    </div>

    <div class="display-field">

        @Html.DisplayFor(model => model.Country)

    </div>

</fieldset>

 

Add and Edit StudentDetails in Views à Home folder.

The purpose of adding StudentDetails view is same as I have explained above for StudentData view.

@model Modal_CRUD_MVC.Models.Student

 

@{

    Layout = null;

}

 

<!DOCTYPE html>

 

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>StudentDetails</title>

</head>

<body>

    <fieldset>

        <legend>Student</legend>

   

        <div class="display-label">

             @Html.DisplayNameFor(model => model.Name)

        </div>

        <div class="display-field">

            @Html.DisplayFor(model => model.Name)

        </div>

   

        <div class="display-label">

             @Html.DisplayNameFor(model => model.Age)

        </div>

        <div class="display-field">

            @Html.DisplayFor(model => model.Age)

        </div>

   

        <div class="display-label">

             @Html.DisplayNameFor(model => model.State)

        </div>

        <div class="display-field">

            @Html.DisplayFor(model => model.State)

        </div>

   

        <div class="display-label">

             @Html.DisplayNameFor(model => model.Country)

        </div>

        <div class="display-field">

            @Html.DisplayFor(model => model.Country)

        </div>

    </fieldset>

    <p>

        @Html.ActionLink("Edit", "Edit", new { id = Model.StudentID }, new { @class = "editDialog" }) |

        @Html.ActionLink("Back to List", "Index")

    </p>

</body>

</html>

 

I have finished Model and View portion. Now I am going to explain about the HomeController and its Action methods which are necessary in order to run our application.

Index action returns a View along with the list of students:

    public class HomeController : Controller

    {

        StudentContext db = new StudentContext();

 

        public ActionResult Index()

        {

            return View(db.Students.ToList());

        }

    }

 

Add the AddEditRecord action with the parameter (id) which can be either null or not null. If the id parameter is null it will return empty _StudentData or StudentData, partial view or View respectively otherwise it will find the record of student on the basis of id and passes the student model to the view in order to update the student details.

Here I am also creating a dynamic property ViewBag.IsUpdate to change the button type in view. If the IsUpdate is true it will set button text as Update and if IsUpdate is false then it will be set as Save.

 [HttpGet]

        public ActionResult AddEditRecord(int? id)

        {

            if (Request.IsAjaxRequest())

            {

                if (id != null)

                {

                    ViewBag.IsUpdate = true;

                    Student student = db.Students.Where(m => m.StudentID == id).FirstOrDefault();

                    return PartialView("_StudentData", student);

                }

                ViewBag.IsUpdate = false;

                return PartialView("_StudentData");

            }

            else

            {

                if (id != null)

                {

                    ViewBag.IsUpdate = true;

                    Student student = db.Students.Where(m => m.StudentID == id).FirstOrDefault();

                    return PartialView("StudentData", student);

                }

                ViewBag.IsUpdate = false;

                return View("StudentData");

            }

        }

 

Add the AddEditRecord action which is of HttpPost type to add or update student record. If the cmd contains Save it will add the record of student in the database otherwise update the data of student in the database.

[HttpPost]

        public ActionResult AddEditRecord(Student student, string cmd)

        {

            if (ModelState.IsValid)

            {

                if (cmd == "Save")

                {

                    try

                    {

                        db.Students.Add(student);

                        db.SaveChanges();

                        return RedirectToAction("Index");

                    }

                    catch { }

                }

                else

                {

                    try

                    {

                        Student stud = db.Students.Where(m => m.StudentID == student.StudentID).FirstOrDefault();

                        if (stud != null)

                        {

                            stud.Name = student.Name;

                            stud.Age = student.Age;

                            stud.State = student.State;

                            stud.Country = student.Country;

                            db.SaveChanges();

                        }

                        return RedirectToAction("Index");

                    }

                    catch { }

                }

            }

 

            if (Request.IsAjaxRequest())

            {

                return PartialView("_StudentData", student);

            }

            else

            {

                return View("StudentData", student);

            }

        }

 

To delete the record of students add the DeleteRecord action in the HomeController. This will delete the record of a student from the database on the basis of id.

public ActionResult DeleteRecord(int id)

        {

            Student student = db.Students.Where(m => m.StudentID == id).FirstOrDefault();

            if (student != null)

            {

                try

                {

                    db.Students.Remove(student);

                    db.SaveChanges();

                }

                catch { }

            }

            return RedirectToAction("Index");

        }

 

To view the details of student, add the Details action in your HomeController. This will display the details of a student on the basis of id.

public ActionResult Details(int id)

        {

            Student student = db.Students.Where(m => m.StudentID == id).FirstOrDefault();

            if (student != null)

            {

                if (Request.IsAjaxRequest())

                {

                    return PartialView("_StudentDetails", student);

                }

                else

                {

                    return View("StudentDetails", student);

                }

            }

            return View("Index");

        }

 

Now both coding and design part is over. To test an application, run or debug your application:

 I have added few records during coding. You can add student records by using Create New option.CRUD operation using Modal dialog in ASP.NET MVC

To edit records, just press edit link given for each students in a row.CRUD operation using Modal dialog in ASP.NET MVC

If the JavaScript is turned off, you cannot use modal dialog to add and edit the records of students, then in that case you can use StudentData view to add and edit the records.CRUD operation using Modal dialog in ASP.NET MVC

To delete the record of student, use Delete link.CRUD operation using Modal dialog in ASP.NET MVC

Thanks for reading this article. You can enter your valuable comments and suggestion to improve this article in the comment box.


Perfect

By Dorababu M on   3 years ago
Rohit Kesharwani perfect example thanks for your contribution

code

By Dorababu M on   3 years ago
Can you attach the code please or can you mail me to dora.meka@gmail.com

Dropdownlist

By RICARDO ARANIBAR on   3 years ago
Hi
How would you do if need display value of dropdown list <select??
for example, my dropdownlist is:
value    description
001          DES1
002          DES2

how display you the description?

Dropdownlist

By Rohit Kesharwani on   8 months ago
Hi Ricardo,

I think the link given below will help you:

Nice article.

By Carl Pieterson on   3 years ago
very well explained article.

Nice Article!

By AVADHESH PATEL on   3 years ago
This is awesome article. 
Thanks for sharing your knowledge. carry on.



Add another one column Image

By anil babu on   3 years ago
Thank you so much Lot of helping for me I am new to MVC,
I have one requirement Add one more column in the database ,
I want to Insert ,Update delete,Display Image also
plz help me

Add another one column Image

By John Smith on   8 months ago

Using MVC

By anil babu on   3 years ago
Using MVC,



Not store the values in DB

By anil babu on   3 years ago
Its working fine But not store the values in Database
Why

About ajax validation ?

By Marcello Moreno on   3 years ago
I just included all libraries to use unobtrusive validation (Required, Range, etc) and the submit behaviour stopped to work.
The validation works perfectly, but the submit button doesn't work anymore.
Any ideas ?

Thank you !

Data access block in MVC4

By priyadharsan kb on   3 years ago
Instead of Entity framework, can we use enteprise library for Data access block(includes store procedure calls etc..) ? is it possible ? How?

Data access block in MVC4

By Rohit Kesharwani on   3 years ago

Hi priyadharsan kb,

you can also include and call stored procedure via Entity Framework database first approach.

Thanks.


Data access block in MVC4

By priyadharsan kb on   3 years ago
Hi Rohit,
Its ok with Entityframework. Is it possible to use enterprise lib in MVC4????

thank you

Data access block in MVC4

By Rohit Kesharwani on   3 years ago
yes you can use enterprise library in MVC.

Mahesh Alle

By mahesh alle on   2 years ago
Very very thanks for posting this. I am relay thank full to you. Grate.... This is very help full for me. Thanks a lot.

Nice Example

By Indra Sena on   2 years ago
I tried the code but can get the dialog only on  first click . There are no errors in the script can u mail me the code isrb.net@gmail.com

Hi .i am new in mvc...I need same code for doing mvc2 web application..

By anoop chandran on   2 years ago
its good....i am new in mvc...i need code for mvc2 web application crud operation using modal dialog in ASP.NET...my mail id - clanoopchandran@gmail.com

ajaxrequest

By Renzo Martinez on   2 years ago
Why "request.isajaxrequest()" always false? I have tried referencing "~/Scripts/jquery.unobtrusive-ajax.min.js" buy not work. Help me, please. I'm working with MVC4 and VS2010.

Saving Twice

By Hadeel Mohammad on   2 years ago
the Edit and Delete code is working normally but I am having problem with the Create New
when I click save the record is saved twice in the database. I debugged it and found that each instruction in the AddEditRecord action is being executed twice!! Any Idea??
I'm working with vs2013 MVC4

Where is the updateTargetID

By Hamzaoui Mounir on   2 years ago
@using (Ajax.BeginForm("create", "Employee", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "studentDialog" }))
Where is the studentDialog ?


Where is the updateTargetID

By Rohit Kesharwani on   2 years ago
Hi Hamzaoui Mounir,

Actually i refresh the whole page after add or update.
you can can give the id of table as given below, so it will update the table section after add, update and delete.

<table cellpadding="10" style="border: 1px solid black; font-family: Verdana;" align="center"

        width="800px">

</table>



which name sapce require

By Parth Patel on   2 years ago

pls giv me solution for this m begginer for mvc...


public class Student

    {

        public int StudentID {  get;  set; }

        public string Name { getset; }

        public string Age { getset; }

        public string State { getset; }

        public string Country { getset; }

    }

    public class StudentContext : DbContext

    {

        public DbSet<Student> Students

        {

            get;

            set;

        }

    } when i add studen class in model folder 

i found Red Line under the DbContext

so which namespace i need to add to solve this problem 


which name sapce require

By Rohit Kesharwani on   2 years ago
you need to add namespace:
using System.Data.Entity;

which resides in Entity Framework package. If Entity Framework package is not exist in your project you can add via package manager console by using command given below:
install-package entityframework

Thank you msg

By Parth Patel on   2 years ago

Thank You Very much For Your Response...


one more problem

By Parth Patel on   2 years ago

[HttpPost]

 public ActionResult AddEditRecord(Student s, string cmd)

i found following errorat AddEditRecord in [HttpPost]

Error

'CRUD_Operation_using_Model_Dialog.Controllers.HomeController.AddEditRecord(CRUD_Operation_using_Model_Dialog.Models.Student, string)': not all code paths return a value


what is the solution for it



one more problem.

By Rohit Kesharwani on   2 years ago
This is your programming fault. I think your method is not return anything in some case.
Please post complete code of method, so that I can rectify.

code of my HttpPost Method

By Parth Patel on   2 years ago

        [HttpPost]

        public ActionResult AddEditRecord(Student s, string cmd)

        {

            if (ModelState.IsValid)

            {

                if (cmd == "Save")

                {

                    try

                    {

                        db.Students.Add(s);

                        db.SaveChanges();

                        return RedirectToAction("Index");

                    }

                    catch { }

                }

                else

                {

                    if (cmd == "Update")

                    try

                    {

                        Student stud = db.Students.Where(m => m.StudentID == s.StudentID).FirstOrDefault();

                        if (stud != null)

                        {

                            stud.Name = s.Name;

                            stud.Age = s.Age;

                            stud.State = s.State;

                            stud.Country = s.Country;

                            db.SaveChanges();

                        }

                        return RedirectToAction("Index");

                    }

                    catch { }

                }

                if (Request.IsAjaxRequest())

                {

                    return PartialView("_StudentData", s);

                }

                else

                {

                    return View("StudentData",s);

                }

            }


        }


code of my HttpPost Method

By Rohit Kesharwani on   2 years ago
replace your code with below one:
your mistake is highlighted in bold:

[HttpPost]
        public ActionResult AddEditRecord(Student s, string cmd)
        {
            if (ModelState.IsValid)
            {
                if (cmd == "Save")
                {
                    try
                    {
                        db.Students.Add(s);
                        db.SaveChanges();
                        return RedirectToAction("Index");
                    }
                    catch { }
                }
                else
                {
                    if (cmd == "Update")
                        try
                        {
                            Student stud = db.Students.Where(m => m.StudentID == s.StudentID).FirstOrDefault();
                            if (stud != null)
                            {
                                stud.Name = s.Name;
                                stud.Age = s.Age;
                                stud.State = s.State;
                                stud.Country = s.Country;

                                db.SaveChanges();

                            }

                            return RedirectToAction("Index");
                        }
                        catch { }
                }
            }
            if (Request.IsAjaxRequest())
            {
                return PartialView("_StudentData", s);
            }
            else
            {
                return View("StudentData", s);
            }
        }

oops...

By Parth Patel on   2 years ago

Thank you very much...ya i found the mistake done by me....

and i want to inform u that this is the best artical for begginer to learn crud operatoin in mvc...

carry on sir....


MVC

By John Smith on   2 years ago
Yes ..Good Article for beginners...
Keep Posting Rohit!!

MVC Javascript error

By Nico Maes on   2 years ago
Thank you for this article. It helped a great deal.

I only receive the following errors when I'm using this for my MVC 5 website.
0x800a138f - JavaScript runtime error: Unable to get property 'appendChild' of undefined or null reference
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'live'
0x800a139e - JavaScript runtime error: InvalidStateError

Has this something to do with the versions of javacript I'm using?

I'm using version 1.10.2 of javascript and version 1.10.4 of the javascript ui.

Thank you in advance.

Regards.

Not able to undestand Path

By Vasu Gummadiadala on   2 years ago
Hi,

I'm not able understand what is Partial view and all,..

can u please send me the code...

so that I can easily find out ...
Please send me the code to "vasuarya143all@gmail.com" 

Thanks,
VasuArya

Perfect Solution

By Vasu Gummadiadala on   2 years ago
Good Article

question regarding catch() retrun partial view

By laura deng on   2 years ago
Hi, Rohit: Your code is very helpful. I tried the create function and it works great. Except that if there is an error been catched int he create function, the Catch() return a partial view, the problem is that partial view does not show in the dialog box anymore, it open as a new page by itself. Do I miss anything. Can you send your code to me at laura.deng@symetra.com ? Thanks much! Laura

source code request

By anil kumar on   2 years ago
source code please 
cd10anil at gmail.com

 the pop window for me appear in new view rather than popup.


Question regarding Request.IsAjaxRequest()

By Teja Gudivada on   2 years ago
What is the use of Request.IsAjaxRequest() in the code it is always returning false


Thank you

Source Code request

By Teja Gudivada on   2 years ago
Can u send the source code to tejaswikumar286@gmail.com please

Thank you

Attach sample code

By Ankita Dengare on   2 years ago
Can You please attach the source code please.... Thank You

great post!! but... I can´t implement using bootstrap and MVC5 ef6

By greg DORIAN on   2 years ago
Hi rohit.

I've was trying to  implement using bootstrap and MVC5 ef6, with modals (http://getbootstrap.com/javascript/#modals) but I don´t know where I have to put the code for the modal, I put it in Index view page, or I have to put in every view included de partial views?? if you have an example it will be wonderful!!

Bootstrap Modal

By Rohit Kesharwani on   2 years ago
you should include the following in every partial view which is rendered in modal:

<div class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <!-- place your controls here -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

thank you !!

By greg DORIAN on   2 years ago
thx rohit!!

Another Great Work buddy

By Madhu Mangalagiri on   2 years ago
Nice Job...

It's fine, but modal popup isn't working

By Lenny Arias on   one year ago
Hi Chris, thank's you for the example. It's work fine for me, but the modal popup's isn't working.

I try the example with Visual Studio 2013 and Mvc4.

Also, i update the jquery version:

<link href="@Url.Content("~/Content/themes/base/minified/jquery-ui.min.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-2.1.3.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.11.2.min.js")" type="text/javascript"></script>

So i get it: