Tuesday, 11 February 2014

Crud operation in mvc using Modal popup

Crud Operation in MVC using Modal Popup

Today we discus about crud operation in mvc with  modal  Popup


first we create database in sql server 

create database dbMVC
use dbMVC

create table stuinfo(id int identity(101,1) primary key,
[user_name] varchar(40),
[LastName] [varchar](40) NULL,
[phone] [bigint] NULL,
[User_address] [varchar](250) NULL)

For creating entity framework use previous post


code for database.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;

namespace User_Registration.Models
{
    public class database : DbContext
    {
        public database()
            : base("ConStr")
        {
        }
        public DbSet<clsUser_info> tbluserinformation { get; set; }
    }
}

Code for clsUser_info.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace User_Registration.Models
{
    [Table("stuinfo")]
    public class clsUser_info
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
        [Required(ErrorMessage="*")]
        [StringLength(30,ErrorMessage="Name should be less than 30")]
        public string usr_name { set; get; }
        [Required(ErrorMessage = "*")]
        [StringLength(15, ErrorMessage = "Password length should be less than 15")]
        public string LastName { set; get; }
        [Required (ErrorMessage ="*")]
        //[StringLength(10,ErrorMessage="Contact number length should be 10 degite")]
        public Int64 phone { set; get; }
        [Required(ErrorMessage ="*")]
        public string User_address { set; get; }
    }
}
Code for IUserInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace User_Registration.Models
{
    interface IUserInfo
    {
        void insert(clsUser_info objUserInfo);
        void update(clsUser_info objUserInfo);
        void delete(int id);
        IList<clsUser_info> List_User_info();
        clsUser_info SearchUser(int? id);
       
    }
}

Code implemented class clsImp_UserInfo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using User_Registration.Models;

namespace User_Registration.Models
{
    public class clsImp_UserInfo:IUserInfo
    {
        database db=new database ();

       
        public void insert(clsUser_info objUserInfo)
        {
            db.tbluserinformation.Add(objUserInfo);
            db.SaveChanges();
        }

        public void update(clsUser_info objUserInfo)
        {
            var v = SearchUser(objUserInfo.id);
            if (v != null)
            {
                v.usr_name = objUserInfo.usr_name;
                v.phone = objUserInfo.phone;
                v.LastName = objUserInfo.LastName;
                v.User_address = objUserInfo.User_address;
                db.SaveChanges();
            }

        }

        public void delete(int id)
        {
            var v = SearchUser(id);
            if (v != null)
            {
                db.tbluserinformation.Remove(v);
                db.SaveChanges();
            }
        }

        public IList<clsUser_info> List_User_info()
        {
            var v = db.tbluserinformation.ToList();
            return v;
        }

        public clsUser_info SearchUser(int? id)
        {

            return db.tbluserinformation.FirstOrDefault(m => m.id == id);

        }
    }
}

Code for Home Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using User_Registration.Models;

namespace User_Registration.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        IUserInfo IUInfo;
        public HomeController()
        {
            IUInfo = new clsImp_UserInfo();
        }
        public ActionResult IndexList()
        {
            return View(IUInfo.List_User_info());
        }
        [HttpGet]
        public ActionResult InsertUpdate(int? id)
        {
            if (Request.IsAjaxRequest())
            {
                if (id != null)
                {
                    ViewBag.IsUpdate = true;
                    clsUser_info objclsUser_info = IUInfo.SearchUser(id);
                    return PartialView("_AddEditView", objclsUser_info);
                }
                ViewBag.IsUpdate = false;
                return PartialView("_AddEditView");
            }
            else
            {
                if (id != null)
                {
                    ViewBag.IsUpdate = true;
                    clsUser_info objclsUser_info = IUInfo.SearchUser(id);
                    return PartialView("AddEditView", objclsUser_info);
                }
                ViewBag.IsUpdate = false;
                return PartialView("AddEditView");

            }



        }
        [HttpPost]
        public ActionResult InsertUpdate(clsUser_info objclsuserinfo, string cmd)
        {
            if (ModelState.IsValid)
            {
                if (cmd == "Save")
                {
                    try
                    {
                        IUInfo.insert(objclsuserinfo);
                        return RedirectToAction("IndexList");
                    }
                    catch { }
                }
                else
                {
                    try
                    {

                        if (objclsuserinfo != null)
                        {
                            IUInfo.update(objclsuserinfo);
                        }
                        return RedirectToAction("IndexList");
                    }
                    catch { }
                }
            }

            if (Request.IsAjaxRequest())
            {
                return PartialView("_AddEditView", objclsuserinfo);
            }
            else
            {
                return View("AddEditView", objclsuserinfo);
            }
        }
        public ActionResult Details(int id)
        {
            clsUser_info objSearch = IUInfo.SearchUser(id);
            if (objSearch != null)
            {

                if (Request.IsAjaxRequest())
                {
                    return PartialView("_Details", objSearch);
                }
                else
                {
                    return View("Details", objSearch);
                }
            }
            return View("IndexList");
        }


        public ActionResult Delete(int id)
        {
            clsUser_info objclsuserinfo = IUInfo.SearchUser(id);
            if (objclsuserinfo != null)
            {
                try
                {
                    IUInfo.delete(id);
                }
                catch { }
            }
            return RedirectToAction("IndexList");
        }

    }
}

Code for IndexList View:-



@model IEnumerable<User_Registration.Models.clsUser_info>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="~/Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.8.20.min.js"></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: 290,
                    width: 400,
                   show: { effect: 'drop', direction: "down",delay:100 },
                    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 Student',
                    autoOpen: false,
                    resizable: false,
                    height: 290,
                    width: 400,
                    show: { effect: 'drop', direction: "down", delay: 100 },
                    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: 190,
                    width: 350,
                    title:'Delete Student',
                    show: { effect: 'drop', direction: "down", delay: 100 },
                    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 Student',
                    autoOpen: false,
                    resizable: false,
                    height: 290,
                    width: 400,
                    show: { effect: 'slide', direction: "left", delay: 100 },
                    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", "InsertUpdate", "Home", null, new { @id = "openDialog" })
            </td>
        </tr>
    </table>
    <table cellpadding="10" style=" font-family: Verdana;" align="center"
        width="800px">
        <tr>
            <th>
                First Name
            </th>
            <th>
               Last Name
            </th>
            <th>
                Email Id
            </th>
             <th>
               Phone
            </th>
            <th>
               Address
            </th>
            <th>
            </th>
        </tr>
        @if (Model.Count() >= 1)
        {
            foreach (var item in Model)
            {
            <tr style="border:solid 1px black;">
              <td>
                  @Html.DisplayFor(modelitem => item.usr_name)
              </td>
                <td>
                    @Html.DisplayFor(modelitem => item.LastName)
                </td>
                <td>@Html.DisplayFor(modelitem => item.phone)</td>
                <td>@Html.DisplayFor(modelitem => item.User_address)</td>
                <td>
                    @Html.ActionLink("Edit", "InsertUpdate", new { id = item.id }, new { @class = "editDialog" })|
                    @Html.ActionLink("Details", "Details", new { id = item.id }, new { @class = "viewDialog" }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.id }, new { @class = "confirmDialog" })
                </td>
            </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="5">Record not found </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>

Code for _AddEditView.cshtml view



@model User_Registration.Models.clsUser_info

<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Ajax.BeginForm("InsertUpdate", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "Dialog" }))
{
    @Html.ValidationSummary(true)

  
        if (ViewBag.IsUpdate == true)
        {
            @Html.HiddenFor(model => model.id)
        }
        <table>
            <tr>
                <td>
                    <div class="editor-label">
                        First Name
                    </div>
                </td>

                <td></td>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.usr_name)
                        @Html.ValidationMessageFor(model => model.usr_name)
                    </div>
                </td>



            </tr>
            <tr>
                <td>
                    <div class="editor-label">
                        Last Name
                    </div>
                </td>
                <td></td>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.LastName)
                        @Html.ValidationMessageFor(model => model.LastName)
                    </div>
                </td>


            </tr>

            <tr>
                <td>
                    <div class="editor-label">
                        Address
                    </div>
                </td>
                <td></td>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.User_address)
                        @Html.ValidationMessageFor(model => model.User_address)
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="editor-label">
                        Phone
                    </div>
                </td>
                <td></td>
                <td>
                    <div class="editor-field">
                        @Html.TextBoxFor(model => model.phone)
                       
                    </div>
                    @Html.ValidationMessageFor(model => model.phone)
                </td>
            </tr>
             <tr>
                <td></td>
                 </tr>
            <tr>
                <td></td>
                <td></td>
                <td> @if (ViewBag.IsUpdate == true)
            {
                <input type="submit" value="Update" name="cmd" />
            }
            else
            {
                <input type="submit" value="Save" name="cmd" />
            }
                     <input type="button" value="Cancel" id="btncancel" />
                </td>
            </tr>
        </table>
       
   
}


Code for AddEditView.cshtml




@model User_Registration.Models.clsUser_info

<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Ajax.BeginForm("InsertUpdate", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "studentDialog" }))
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Student</legend>
        @if (ViewBag.IsUpdate == true)
        {
            @Html.HiddenFor(model => model.id)
        }
        <table>
            <tr>
                <td>
                    <div class="editor-label">
                        First Name
                    </div>
                </td>

                <td></td>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.usr_name)
                        @Html.ValidationMessageFor(model => model.usr_name)
                    </div>
                </td>



            </tr>
            <tr>
                <td>
                    <div class="editor-label">
                        Last Name
                    </div>
                </td>
                <td></td>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.LastName)
                        @Html.ValidationMessageFor(model => model.LastName)
                    </div>
                </td>


            </tr>

            <tr>
                <td>
                    <div class="editor-label">
                        Address
                    </div>
                </td>
                <td></td>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.User_address)
                        @Html.ValidationMessageFor(model => model.User_address)
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <div class="editor-label">
                        Phone
                    </div>
                </td>
                <td></td>
                <td>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.phone)
                        @Html.ValidationMessageFor(model => model.phone)
                    </div>
                </td>
            </tr>
        </table>
        <p>
            @if (ViewBag.IsUpdate == true)
            {
                <input type="submit" value="Update" name="cmd" />
            }
            else
            {
                <input type="submit" value="Save" name="cmd" />
            }
            <input type="button" value="Cancel" id="btncancel" />
        </p>
    </fieldset>
}


Code for _Details.cshtml


@model User_Registration.Models.clsUser_info

   

        <table>
            <tr>
                <td colspan ="3"></td>
            </tr>
             <tr>
                <td colspan ="3"></td>
            </tr>
             <tr>
                <td colspan ="3"></td>
            </tr>
            <tr>
               <td>First Name</td>
                <td></td>
                <td>@Html.DisplayFor(model=>model.usr_name )</td>

            </tr>
            <tr><td colspan="3"></td></tr>
            <tr>
               <td>Last Name</td>
                <td></td>
                <td>@Html.DisplayFor(model=>model.LastName )</td>

            </tr>
             <tr><td colspan="3"></td></tr>
            <tr>
               <td>Contact Number</td>
                <td></td>
                <td>@Html.DisplayFor(model=>model.phone )</td>

            </tr>
             <tr><td colspan="3"></td></tr>
            <tr>
               <td>Address</td>
                <td></td>
                <td>@Html.DisplayFor(model=>model.User_address)</td>

            </tr>
        </table>


  
Code for Details.cshtml
@model User_Registration.Models.clsUser_info

   

        <table>
            <tr>
                <td colspan ="3"></td>
            </tr>
             <tr>
                <td colspan ="3"></td>
            </tr>
             <tr>
                <td colspan ="3"></td>
 hjhh           </tr>
            <tr>
               <td>First Name</td>
                <td></td>
                <td>@Html.DisplayFor(model=>model.usr_name )</td>

            </tr>
            <tr><td colspan="3"></td></tr>
            <tr>
               <td>Last Name</td>
                <td></td>
                <td>@Html.DisplayFor(model=>model.LastName )</td>

            </tr>
             <tr><td colspan="3"></td></tr>
            <tr>
               <td>Contact Number</td>
                <td></td>
                <td>@Html.DisplayFor(model=>model.phone )</td>

            </tr>
             <tr><td colspan="3"></td></tr>
            <tr>
               <td>Address</td>
                <td></td>
                <td>@Html.DisplayFor(model=>model.User_address)</td>

            </tr>
        </table>


0 comments: