Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Here i got one requirement ie i have to create one jquery popup which contains two texbox and button....when i click that button i need to save in gridview and popup should close...

Actually i searched in google.....i didn't got proper code.....Here i want in Clientside...
please help me.....
Posted

Hi
I feel this link may help you


Update/delete data in gridview[^]
 
Share this answer
 
Comments
Member 9155255 1-Oct-13 7:22am    
Thanks for the Link...here i want to bind grid within jquery script....i can't bind within the static method.....or i want to call a method which binds grid within a webservice method....

please help me
VishwaKL 3-Oct-13 0:24am    
yes i feel better use web service to bind with help of jquery
this is for index.cshtml page:-
XML
@using TestDemo16_nov.Models;
@model List<UserViewModel>

@{
    ViewBag.Title = "Home Page";
}
@*<link href="~/Content/Jq%20grid/jquery-ui-custom.css" rel="stylesheet" />*@
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/Jqgrid/jquery-ui-1.8.7.css" rel="stylesheet" />
<link href="~/Content/Jqgrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/Jqgrid/grid.locale-en.js"></script>
<script src="~/Scripts/Jqgrid/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<style type="text/css">
    .userRow {
        color: #0769AD !important;
    }
</style>

<script type="text/javascript">

    /****************this is to edit the user**********************/
    function EditUser(id) {
        $.ajax({
            url: "@Url.Action("EditUser", "Home")" + "?id=" + id,
            data: "userId=" + id,
            success: function (result) {
                $("#divEditUser").html(result);
                $("#divEditUser").dialog("open");
            }
        });

    }
    /*******************this is used to start the overlay(loader)***********************/
    function loaderStart() {
        $('#loader').show();
    }
    /*******************this is used to stop the overlay(loader)***********************/
    function loaderStop() {
        setTimeout('$("#loader").hide()', 100);
    }

    /****************this is to delete the user**********************/
    function DeleteUser(id) {
        var r = confirm("Do you want to delete this User?");

        if (r == true) {
            $.ajax({
                type: "POST",
                url: "/Home/DeleteUser",
                async: false,
                data: "userId=" + id,
                success: function (data) {
                    if (data == 'True') {
                        RefreshGrid();
                        alert('User deleted successfully.');
                    }
                    else {
                        alert('Some error is occured while deleting.');
                    }
                }

            });
        }
    }

    /********************To refresh grid****************/
    function RefreshGrid() {
        $("#list").jqGrid().setGridParam({
            url: '/Home/LinqGridData/',
            datatype: 'json'
        }).trigger("reloadGrid");
    }

    $(function () {
        /******************this is used to add new user*******************/
        $("#AddUser").click(function () {

            $.ajax({
                url: "@Url.Action("EditUser", "Home")" + "?id=" + 0,
                success: function (result) {
                    $("#divEditUser").html(result);
                    $("#divEditUser").dialog("open");
                }
            });
        });

        /******************this is used to open dialog for user Add/Edit*******************/
        $("#divEditUser").dialog({
            autoOpen: false,
            show: {
                effect: "blind",
                duration: 1000
            },
            hide: {
                effect: "explode",
                duration: 1000
            }
        });
        /******************this is used to show user*******************/
        $("#list").jqGrid({
            url: '/Home/LinqGridData/',
            datatype: 'json',
            mtype: 'GET',
            colNames: ['Id', 'Name', 'Email', 'Action'],
            colModel: [
          { name: 'Id', index: 'Id', width: 120, align: 'center', hidden: true },
          { name: 'Name', index: 'Id', width: 170, align: 'center' },
         { name: "Email", index: 'Email', width: 170, align: 'center' },
          { name: 'act', width: 138, sortable: false }
            ],
            pager: $('#pager'),
            rowNum: 5,
            rowList: [5, 10, 15, 20, 50],
            sortname: 'Id',
            sortorder: 'desc',
            sortable: true,
            height: "100%",
            viewrecords: true,
            imgpath: '',
            caption: 'User List',
            gridComplete: function () {
                var ids = $("#list").jqGrid('getDataIDs');
                var myCellData;
                for (var i = 0; i < ids.length; i++) {
                    var cl = ids[i];
                    var grid = $('#list');
                    myCellData = grid.jqGrid('getCell', cl, 'Id');
                    ed = "<input style='height:30px;width:50px;' type='button' value='Edit' onclick=\"EditUser(" + myCellData + ");\" />";
                    de = "<input style='height:30px;width:70px;' type='button' value='Delete' onclick=\"DeleteUser(" + myCellData + ");\" />";
                    $("#list").jqGrid('setRowData', ids[i], { act: ed + "|" + de });
                }
            }
        });
    });
</script>
<form id="frmUser">
    <a href="#" id="AddUser">Add User</a>
    <fieldset>
        <legend class="fieldset">User List</legend>
        <table id="list" class="scroll" cellpadding="0" cellspacing="0">
        </table>
        <div id="pager" class="scroll" style="text-align: center;">
        </div>
    </fieldset>

</form>

<!--this div for edit/add user-->
<div id="divEditUser" title="Basic dialog">
</div>

<!--loader div start here-->
<div class="loader" id="loader" style="display: none">
    <span class="ui-icon">&nbsp;</span>
</div>






:-----------------------
in the above code you find everything that you required...

controller code is given bellow:-

XML
using System.Web;
using System.Web.Mvc;
using TestDemo16_nov.Models;
namespace TestDemo16_nov.Controllers
{
    /// <summary>
    /// this is used for user
    /// </summary>
    public class HomeController : Controller
    {
        private testDBEntities dbEntities = new testDBEntities();
        /// <summary>
        /// this is used to show the all user information list.
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var lstUser = (from user in dbEntities.tblusers
                           select new UserViewModel
                           {
                               Id = user.id,
                               Name = user.Name,
                               Email = user.Email
                           }).OrderByDescending(c=>c.Id).ToList();

            return View(lstUser);
        }

        /// <summary>
        /// To delete user data
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public bool DeleteUser(string userId)
        {
            try
            {
                int id = Convert.ToInt32(userId);
                var objUser = dbEntities.tblusers.Where(c => c.id == id).FirstOrDefault();
                dbEntities.tblusers.Remove(objUser);
                dbEntities.SaveChanges();
                return true;
            }
            catch (Exception)
            {

                return false;
            }
        }
        /// <summary>
        /// To edit user data
        /// </summary>
        /// <returns></returns>
        public ActionResult EditUser(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new FieldAccessException();
            }
            if (id.Equals("0"))
            {
                var user = new UserViewModel();
                return PartialView(user);
            }
            else {
                int userId = Convert.ToInt32(id);
                var objUser = dbEntities.tblusers.Where(c => c.id == userId).FirstOrDefault();
                var user = new UserViewModel
                {
                    Id = objUser.id,
                    Name = objUser.Name,
                    Email = objUser.Email
                };
                return PartialView(user);
            }


        }

        [HttpPost]
        /// <summary>
        /// To edit user data
        /// </summary>
        /// <returns></returns>
        public ActionResult EditUser(UserViewModel model)
        {

            if (model.Id == 0)
            {
                var newUser = new tbluser
                {
                    Email=model.Email,
                    Name=model.Name
                };
                dbEntities.tblusers.Add(newUser);
                dbEntities.SaveChanges();
                return RedirectToAction("Index");
            }

            var objUser = dbEntities.tblusers.Where(c => c.id == model.Id).FirstOrDefault();
            objUser.Email = model.Email;
            objUser.Name = model.Name;
            dbEntities.SaveChanges();
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Function to bind Grid Data
        /// </summary>
        /// <param name="sidx"></param>
        /// <param name="sord"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        public ActionResult LinqGridData(string sidx, string sord, int page, int rows)
        {
            int pageSize = rows;

            int pageIndex = Convert.ToInt32(page) - 1;

            var lstUser = (from user in dbEntities.tblusers
                           select new UserViewModel
                           {
                               Id = user.id,
                               Name = user.Name,
                               Email = user.Email
                           }).OrderByDescending(c=>c.Id).ToList();

            int totalRecords = lstUser.Count;

            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            lstUser = lstUser.Skip(pageIndex * pageSize)
               .Take(pageSize).ToList();

            var jsonData = new
            {
                total = totalPages, //todo: calculate
                page,
                records = totalRecords,
                rows = (
                    from usr in lstUser
                    select new
                    {
                        i = usr.Id,
                        cell = new string[] { usr.Id.ToString(), usr.Name, usr.Email }
                    }).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }


    
    }
}

-------
you need to create the edmx and bind. one partial view is require so you need to create in Shared folder with name "EditUser" the html code is given bellow :

@model TestDemo16_nov.Models.UserViewModel

<h2>EditUser</h2>

@using (Html.BeginForm())
{ 
    <fieldset>
        <legend>Edit User</legend>
        <ol>
            <li>
                @Html.LabelFor(m => m.Name)
                @Html.TextBoxFor(m => m.Name)
                @Html.ValidationMessageFor(m => m.Name)
            </li>
            <li>
                @Html.LabelFor(m => m.Email)
                @Html.TextBoxFor(m => m.Email)
                @Html.ValidationMessageFor(m => m.Email)
            </li>
        </ol>
        <input type="submit" id="btnSubmit" value="Save" />
    </fieldset>
}

----
here I am using UserViewModel model so please create it like given bellow:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestDemo16_nov.Models
{
    /// <summary>
    /// this is used fatch/insert the user information from the database table tbluser.
    /// </summary>
    public class UserViewModel
    {
        /// <summary>
        /// this is unique key for user. 
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// this is for email of user.
        /// </summary>
        public string  Email { get; set; }
        
        /// <summary>
        /// this is used to name of user.
        /// </summary>
        public string  Name { get; set; }

    }
}
-----------------
 
Share this answer
 
v2
Comments
ashok rathore 20-Nov-13 3:02am    
hi,
I have done these requirement in mvc4.
Please you need to download the js/css using google.

Bellow url help you to download the js and css.

http://jqueryui.com/dialog/
http://trirand.com/blog/jqgrid/jqgrid.html

Thanks,

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900