【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

时间:2022-09-18 09:38:49

ASP.NET MVC系列文章

【01】浅谈Google Chrome浏览器(理论篇)

【02】浅谈Google Chrome浏览器(操作篇)(上)

【03】浅谈Google Chrome浏览器(操作篇)(下)

【04】浅谈ASP.NET框架

【05】浅谈ASP.NET MVC运行过程

【06】浅谈ASP.NET MVC 控制器

【07】浅谈ASP.NET MVC 路由

【08】浅谈ASP.NET MVC 视图

【09】浅谈ASP.NET MVC 视图与控制器传递数据

【10】浅谈jqGrid 在ASP.NET MVC中增删改查

【11】浅谈ASP.NET 页面之间传值的几种方式

【12】浅谈缓存技术在ASP.NET中的运用

【13】浅谈NuGet在VS中的运用

【14】浅谈ASP.NET 程序发布过程

【15】浅谈数据注解和验证

【16】浅谈依赖注入

【17】浅谈表单和HTML辅助方法

【18】浅谈基于APS.NET身份验证

【19】浅谈ASP.NET MVC 模型

【20】浅谈ASP.NET MVC 单元测试

【21】浅谈ASP.NET MVC网络安全;

【22】浅谈ASP.NET MVC八大类扩展

【23】再谈ASP.NET MVC Routing

【24】浅谈ASP.NET 高级话题

【25】浅谈大型ASP.NET MVC项目(含DEMO)

【26】下一系列:ASP.NET WebAPI

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查


1   概述

本篇文章主要是关于JqGrid的,主要功能包括使用JqGrid增删查改,导入导出,废话不多说,直接进入正题。

2   Demo相关

2.1   Demo展示

第一部分

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

第二部分

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

2.2  源码和DB下载

本来国庆上传到github上的,现在github有点问题,因此后期再传到github,有需要源码的,可以在评论区留下自己联系联系方式,我直接传给你。

3  公共模块

3.1 Model实体—EmployeeInfo

 using MVCCrud.Areas.DBUtility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web; namespace MVCCrud.Areas.JqGridDemo.Models
{
//EmployeeInfo实体类
public class EmployeeInfo
{
public string EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string EmployeeMajor { get; set; }
public string EmployeeDepartment { get; set; }
public string EmployeeTel { get; set; }
public string EmployeeEmail { get; set; }
public string EmployeeJiGuan { get; set; }
public string EmployeeAddress { get; set; }
public string EmployeePosition { get; set; }
public DateTime EmployeeBirthday { get; set; }
}
}

3.2  DBHelper帮助类

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI.WebControls; namespace MVCCrud.Areas.DBUtility
{
public abstract class DbHelperSQL
{
/*
* content:DbHelper帮助类
*author:Alan_beijing
* date:2017-10-01
*/
public DbHelperSQL()
{
//构造函数
}
protected static string ConnectionString = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
protected static SqlConnection Connection;
//定义数据库的打开和关闭方法
protected static void Open()
{
if (Connection == null)
{
Connection = new SqlConnection(ConnectionString);
}
if (Connection.State.Equals(ConnectionState.Closed))
{
Connection.Open();
}
}
protected static void Close()
{
if (Connection != null)
{
Connection.Close();
}
} // 公有方法,获取数据,返回一个DataSet。
public static DataSet GetDataSet(string SqlString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(SqlString, connection))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
connection.Close();
return ds;
}
}
}
}
// 公有方法,获取数据,返回一个DataTable。
public static DataTable GetDataTable(string SqlString)
{
DataSet dataset = GetDataSet(SqlString);
return dataset.Tables[];
}
public static int ExecuteSQL(String SqlString, Hashtable MyHashTb)
{
int count = -;
SqlConnection connectiontemp = new SqlConnection(ConnectionString);
connectiontemp.Open();
try
{
SqlCommand cmd = new SqlCommand(SqlString, connectiontemp);
foreach (DictionaryEntry item in MyHashTb)
{
string[] CanShu = item.Key.ToString().Split('|');
if (CanShu[].ToString().Trim() == "string")
{
cmd.Parameters.Add(CanShu[], SqlDbType.VarChar);
}
else if (CanShu[].ToString().Trim() == "int")
{
cmd.Parameters.Add(CanShu[], SqlDbType.Int);
}
else if (CanShu[].ToString().Trim() == "text")
{
cmd.Parameters.Add(CanShu[], SqlDbType.Text);
}
else if (CanShu[].ToString().Trim() == "datetime")
{
cmd.Parameters.Add(CanShu[], SqlDbType.DateTime);
}
else
{
cmd.Parameters.Add(CanShu[], SqlDbType.VarChar);
}
cmd.Parameters[CanShu[]].Value = item.Value.ToString();
}
count = cmd.ExecuteNonQuery();
}
catch
{
count = -;
}
finally
{
connectiontemp.Close();
}
return count;
}
// 公有方法,执行Sql语句。对Update、Insert、Delete为影响到的行数,其他情况为-1
public static int ExecuteSQL(String SqlString)
{
int count = -;
SqlConnection connectionTemp = new SqlConnection(ConnectionString);
connectionTemp.Open();
try
{
SqlCommand cmd = new SqlCommand(SqlString, connectionTemp);
count = cmd.ExecuteNonQuery();
}
catch
{
count = -;
}
finally
{
connectionTemp.Close();
}
return count;
}
// 公有方法,执行一组Sql语句。返回是否成功,采用事务管理,发现异常时回滚数据
public static bool ExecuteSQL(string[] SqlStrings)
{
bool success = true;
SqlConnection connectionTemp = new SqlConnection(ConnectionString);
connectionTemp.Open();
SqlCommand cmd = new SqlCommand();
SqlTransaction trans = Connection.BeginTransaction();
cmd.Connection = connectionTemp;
cmd.Transaction = trans;
try
{
foreach (string str in SqlStrings)
{
cmd.CommandText = str;
cmd.ExecuteNonQuery();
}
trans.Commit();
}
catch
{
success = false;
trans.Rollback();
}
finally
{
connectionTemp.Close();
}
return success;
}
// 执行一条计算查询结果语句,返回查询结果(object)。
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
connection.Close();
return null;
}
else
{
connection.Close();
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
return null;
//throw e;
}
}
}
}
public static object GetSingle(string SQLString, int Times)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = Times;
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
connection.Close();
return null;
}
else
{
connection.Close();
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
//throw e;
return null;
}
}
}
}
public static object GetSingle(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
object obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
connection.Close();
return null;
}
else
{
connection.Close();
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
//throw e;
return null;
}
}
}
}
// 执行SQL语句,返回影响的记录数
public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
int rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
connection.Close();
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
//throw e;
return ;
}
}
}
}
//执行查询语句,返回DataSet
public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, connection, null, SQLString, cmdParms);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear(); }
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
connection.Close();
return ds;
}
}
}
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
{
if (conn.State != ConnectionState.Open)
conn.Open();
cmd.Connection = conn;
cmd.CommandText = cmdText;
if (trans != null)
cmd.Transaction = trans;
cmd.CommandType = CommandType.Text;//cmdType;
if (cmdParms != null)
{
foreach (SqlParameter parameter in cmdParms)
{
if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
(parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
cmd.Parameters.Add(parameter);
}
}
}
}
}

4   数据访问层DAL

4.1  对EmployeeInfo的CRUD

 using MVCCrud.Areas.DBUtility;
using MVCCrud.Areas.JqGridDemo.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web; namespace MVCCrud.Areas.DAL
{
public class EmployeeInfoToCRUD
{
/// <summary>
/// 增加一条数据
/// </summary>
/// <param name="employeeInfo">EmployeeInfo对象</param>
/// <returns>添加数据是否成功</returns>
public int DALEmployeeInfoToDdd(EmployeeInfo employeeInfo)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into EmployeeInfo(");
strSql.Append("EmployeeID,EmployeeName,EmployeeMajor,EmployeeDepartment,EmployeeTel,EmployeeEmail,EmployeeJiGuan,EmployeeAddress,EmployeePosition,EmployeeBirthday)");
strSql.Append(" values (");
strSql.Append("@EmployeeID,@EmployeeName,@EmployeeMajor,@EmployeeDepartment,@EmployeeTel,@EmployeeEmail,@EmployeeJiGuan,@EmployeeAddress,@EmployeePosition,@EmployeeBirthday)");
strSql.Append(";select @@IDENTITY");
SqlParameter[] parameters =
{
new SqlParameter("@EmployeeID", SqlDbType.VarChar,),
new SqlParameter("@EmployeeName", SqlDbType.VarChar,),
new SqlParameter("@EmployeeMajor", SqlDbType.Text),
new SqlParameter("@EmployeeDepartment",SqlDbType.VarChar,),
new SqlParameter("@EmployeeTel", SqlDbType.VarChar,),
new SqlParameter("@EmployeeEmail", SqlDbType.VarChar,),
new SqlParameter("@EmployeeJiGuan", SqlDbType.VarChar,),
new SqlParameter("@EmployeeAddress", SqlDbType.VarChar,),
new SqlParameter("@EmployeePosition", SqlDbType.VarChar, ),
new SqlParameter("@EmployeeBirthday", SqlDbType.DateTime)
}; parameters[].Value = employeeInfo.EmployeeID;
parameters[].Value = employeeInfo.EmployeeName;
parameters[].Value = employeeInfo.EmployeeMajor;
parameters[].Value = employeeInfo.EmployeeDepartment;
parameters[].Value = employeeInfo.EmployeeTel;
parameters[].Value = employeeInfo.EmployeeEmail;
parameters[].Value = employeeInfo.EmployeeJiGuan;
parameters[].Value = employeeInfo.EmployeeAddress;
parameters[].Value = employeeInfo.EmployeePosition;
parameters[].Value = employeeInfo.EmployeeBirthday; object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
if (obj == null)
{
return ;
}
else
{
return Convert.ToInt32(obj);
}
} /// <summary>
/// 删除一条数据
/// </summary>
/// <param name="employeeID">查询参数:员工ID</param>
/// <returns>是否成功删除</returns>
public int DALEmployeeInfoToDelete(string employeeID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("DELETE EmployeeInfo");
strSql.Append(" WHERE EmployeeID=@EmployeeID ");
SqlParameter[] parameters = {
new SqlParameter("@EmployeeID",SqlDbType.VarChar,)};
parameters[].Value = employeeID; return DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
} /// <summary>
/// 获取EmployeeInfo数据表
/// </summary>
/// <returns>返回EmployeeInfo数据表</returns>
public DataTable DALEmployeeInfoToGetTable()
{
StringBuilder strSql = new StringBuilder();
strSql.Append("SELECT * FROM EmployeeInfo ");
return DbHelperSQL.GetDataTable(strSql.ToString());
} /// <summary>
/// 根据EmployeeName查询EmployeeInfo实体表数据
/// </summary>
/// <param name="EmployeeName">查询参数:EmployeeName</param>
/// <returns>返回查询到的DataTable</returns>
public DataTable DALEmployeeInfoToGetTable(string EmployeeName)
{
string strSql = @"SELECT * FROM EmployeeInfo WHERE EmployeeName=@EmployeeName";
SqlParameter[] parameters = {
new SqlParameter("@EmployeeName",SqlDbType.VarChar,)
};
parameters[].Value = EmployeeName;
return DbHelperSQL.Query(strSql, parameters).Tables["ds"];
}
/// <summary>
/// 根据employeeInfo条件更新数据
/// </summary>
/// <param name="employeeInfo">更新条件:employeeInfo</param>
public void DALEmployeeInfoToUpdate(EmployeeInfo employeeInfo)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("UPDATE EmployeeInfo SET ");
strSql.Append("EmployeeName=@EmployeeName,EmployeeMajor=@EmployeeMajor,");
strSql.Append("EmployeeDepartment=@EmployeeDepartment,EmployeeTel=@EmployeeTel,EmployeeEmail=@EmployeeEmail,");
strSql.Append("EmployeeJiGuan=@EmployeeJiGuan,EmployeeAddress=@EmployeeAddress,EmployeePosition=@EmployeePosition,EmployeeBirthday=@EmployeeBirthday");
strSql.Append(" WHERE EmployeeID=@EmployeeID");
SqlParameter[] parameters = {
new SqlParameter("@EmployeeID", SqlDbType.VarChar,),
new SqlParameter("@EmployeeName", SqlDbType.VarChar,),
new SqlParameter("@EmployeeMajor", SqlDbType.Text),
new SqlParameter("@EmployeeDepartment",SqlDbType.VarChar,),
new SqlParameter("@EmployeeTel", SqlDbType.VarChar,),
new SqlParameter("@EmployeeEmail", SqlDbType.VarChar,),
new SqlParameter("@EmployeeJiGuan", SqlDbType.VarChar,),
new SqlParameter("@EmployeeAddress", SqlDbType.VarChar,),
new SqlParameter("@EmployeePosition", SqlDbType.VarChar, ),
new SqlParameter("@EmployeeBirthday", SqlDbType.DateTime)
};
parameters[].Value = employeeInfo.EmployeeID;
parameters[].Value = employeeInfo.EmployeeName;
parameters[].Value = employeeInfo.EmployeeMajor;
parameters[].Value = employeeInfo.EmployeeDepartment;
parameters[].Value = employeeInfo.EmployeeTel;
parameters[].Value = employeeInfo.EmployeeEmail;
parameters[].Value = employeeInfo.EmployeeJiGuan;
parameters[].Value = employeeInfo.EmployeeAddress;
parameters[].Value = employeeInfo.EmployeePosition;
parameters[].Value = employeeInfo.EmployeeBirthday; DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
}
}
}

4.2 简要分析

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

5   控制器层

5.1 方法

 using MVCCrud.Areas.JqGridDemo.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCCrud.Areas.DAL; namespace MVCCrud.Areas.JqGridDemo.Controllers
{
public class JqGridCRUDController : Controller
{
// GET: JqGridDemo/JqGridCRUD
//初始视图表
public ActionResult Index()
{
return View();
}
//导入模板
public ActionResult GetEmployeeInfoTemple()
{
string path = Server.MapPath(@"~/Content/Upload/");
string fileName = "EmployeeImport.xlsx";
return File(new FileStream(path + fileName, FileMode.Open, FileAccess.Read), "xls", fileName);
} //预设置初始化数据表
public ActionResult EmployeeInfoToLoad()
{
List<EmployeeInfo> ltPI = new List<EmployeeInfo>();
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
DataTable dt = employeeInfoToCRUD.DALEmployeeInfoToGetTable();
for (int i = ; i < dt.Rows.Count; i++)
{
EmployeeInfo custInfo = new EmployeeInfo();
custInfo.EmployeeID = dt.Rows[i]["EmployeeID"].ToString();
custInfo.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
custInfo.EmployeeMajor = dt.Rows[i]["EmployeeMajor"].ToString();
custInfo.EmployeeDepartment = dt.Rows[i]["EmployeeDepartment"].ToString();
custInfo.EmployeeTel = dt.Rows[i]["EmployeeTel"].ToString();
custInfo.EmployeeEmail = dt.Rows[i]["EmployeeEmail"].ToString();
custInfo.EmployeeJiGuan = dt.Rows[i]["EmployeeJiGuan"].ToString();
custInfo.EmployeeAddress = dt.Rows[i]["EmployeeAddress"].ToString();
custInfo.EmployeePosition = dt.Rows[i]["EmployeePosition"].ToString();
if (dt.Rows[i]["EmployeeBirthday"] != System.DBNull.Value)
{
custInfo.EmployeeBirthday = Convert.ToDateTime(dt.Rows[i]["EmployeeBirthday"]);
}
ltPI.Add(custInfo);
TempData["CustomerInfo"] = ltPI;
}
return Content(ToJsonString(ltPI));
} //预设置添加数据
public void EmployeeInfoToDdd(EmployeeInfo employeeInfo)
{
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
employeeInfoToCRUD.DALEmployeeInfoToDdd(employeeInfo);
}
//预设置删除数据
[HttpPost]
public void EmployeeInfoToDel(string EmployeeID)
{
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
employeeInfoToCRUD.DALEmployeeInfoToDelete(EmployeeID);
} //预设置更新数据
public void EmployeeInfoToUpdate(EmployeeInfo employeeInfo)
{
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
employeeInfoToCRUD.DALEmployeeInfoToUpdate(employeeInfo);
} //预设置查询数据
public ActionResult EmployeeInfoToSearch(string employeeName)
{
List<EmployeeInfo> ltPI = new List<EmployeeInfo>();
EmployeeInfoToCRUD employeeInfoToCRUD = new EmployeeInfoToCRUD();
DataTable dt = employeeInfoToCRUD.DALEmployeeInfoToGetTable(employeeName);
for (int i = ; i < dt.Rows.Count; i++)
{
EmployeeInfo custInfo = new EmployeeInfo();
custInfo.EmployeeID = dt.Rows[i]["EmployeeID"].ToString();
custInfo.EmployeeName = dt.Rows[i]["EmployeeName"].ToString();
custInfo.EmployeeMajor = dt.Rows[i]["EmployeeMajor"].ToString();
custInfo.EmployeeDepartment = dt.Rows[i]["EmployeeDepartment"].ToString();
custInfo.EmployeeTel = dt.Rows[i]["EmployeeTel"].ToString();
custInfo.EmployeeEmail = dt.Rows[i]["EmployeeEmail"].ToString();
custInfo.EmployeeJiGuan = dt.Rows[i]["EmployeeJiGuan"].ToString();
custInfo.EmployeeAddress = dt.Rows[i]["EmployeeAddress"].ToString();
custInfo.EmployeePosition = dt.Rows[i]["EmployeePosition"].ToString();
if (dt.Rows[i]["EmployeeBirthday"] != System.DBNull.Value)
{
custInfo.EmployeeBirthday = Convert.ToDateTime(dt.Rows[i]["EmployeeBirthday"]);
}
ltPI.Add(custInfo);
TempData["CustomerInfo"] = ltPI;
}
return Content(ToJsonString(ltPI));
} /// <summary>
/// 为Oject对象增加ToJsonString方法(注意对项目添加Newtonsoft.Json.dll引用)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public string ToJsonString(Object obj)
{
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return JsonConvert.SerializeObject(obj, jsSettings);
}
}
}

5.2 分析

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

6   展示层

6.1  View  Code

 @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/OuterLibrary/jquery-ui-themes-1.12.1/jquery-ui.css" rel="stylesheet" />
<link href="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/src/css/ui.jqgrid.css" rel="stylesheet" />
<script src="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/js/jquery-1.11.0.min.js"></script>
<script src="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/src/jquery.jqGrid.js"></script>
<script src="//apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script src="~/OuterLibrary/tonytomov-jqGrid-6659334/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
<script src="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/src/grid.export.js"></script>
<script src="~/OuterLibrary/Guriddo_jqGrid_JS_5.2.1/src/grid.import.js"></script>
<title>员工信息表</title>
<script type="text/javascript">
$(document).ready(function () {
//添加
$("#btn_add").click(function () {
//var model = jQuery("#JqGrid-table").jqGrid('getRowData', EmployeeID);
$("#AddEmployeeInfo").dialog({
height: ,
width: ,
resizable: false,
modal: true, //这里就是控制弹出为模态
buttons: {
"确定": function () {
//alert("在这里对数据进行修改!");
//$(this).dialog("close");
//var birthdayTime ="2017/9/28";
var employeeID = $("#ADD_EmployeeID").val();
var employeeName = $("#ADD_EmployeeName").val();
var employeeMajor = $("#ADD_EmployeeMajor").val();
var employeeDepartment = $("#ADD_EmployeeDepartment").val();
var employeeTel = $("#ADD_EmployeeTel").val();
var employeeEmail = $("#ADD_EmployeeEmail").val();
var employeeJiGuan = $("#ADD_EmployeeJiGuan").val();
var employeeAddress = $("#ADD_EmployeeAddress").val();
var employeePosition = $("#ADD_EmployeePosition").val();
var employeeBirthday = $("#ADD_EmployeeBirthday").val();
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToDdd",
type: "GET",
data: {
EmployeeID: employeeID, EmployeeName: employeeName, EmployeeMajor: employeeMajor,
EmployeeDepartment: employeeDepartment, EmployeeTel: employeeTel, EmployeeEmail: employeeEmail,
EmployeeJiGuan: employeeJiGuan, EmployeeAddress: employeeAddress, EmployeePosition: employeePosition,
EmployeeBirthday: employeeBirthday
},
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('添加数据成功'); },
error: function (message) {
alert('error!');
}
});
},
"取消": function () {
$(this).dialog("close");
}
}
});
});
//删除
$("#btn_del").click(function () {
var employeeID = $('#JqGrid-table').jqGrid('getGridParam', 'selrow');//获取行id
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToDel",
type: "post",
data: { EmployeeID: employeeID },
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('成功删除一条数据');
},
error: function (message) {
alert('error!');
}
});
});
//编辑
$("#btn_edit").click(function () {
//var ids = jQuery("#JqGrid-table").jqGrid('getDataIDs');//返回grid里所有数据的id
var id = jQuery("#JqGrid-table").jqGrid('getGridParam', 'selarrrow');
var EmployeeInfoModel = jQuery("#JqGrid-table").jqGrid('getRowData', id);
$("#Modify_EmployeeID").val(EmployeeInfoModel.EmployeeID);
$("#Modify_EmployeeName").val(EmployeeInfoModel.EmployeeName);
$("#Modify_EmployeeMajor").val(EmployeeInfoModel.EmployeeMajor);
$("#Modify_EmployeeDepartment").val(EmployeeInfoModel.EmployeeDepartment);
$("#Modify_EmployeeTel").val(EmployeeInfoModel.EmployeeTel);
$("#Modify_EmployeeEmail").val(EmployeeInfoModel.EmployeeEmail);
$("#Modify_EmployeeJiGuan").val(EmployeeInfoModel.EmployeeJiGuan);
$("#Modify_EmployeeAddress").val(EmployeeInfoModel.EmployeeAddress);
$("#Modify_EmployeePosition").val(EmployeeInfoModel.EmployeePosition);
$("#Modify_EmployeeBirthday").val(EmployeeInfoModel.EmployeeBirthday);
$("#ModifyEmployeeInfo").dialog({
height: ,
width: ,
resizable: false,
modal: true, //这里就是控制弹出为模态
buttons: {
"确定": function () {
//alert("在这里对数据进行修改!");
//$(this).dialog("close");
//var birthdayTime ="2017/9/28";
//$("#Modify_EmployeeEmployeeName").value = 'ddd';
//提交前的初始值
var employeeID = $("#Modify_EmployeeID").val();
var employeeName = $("#Modify_EmployeeName").val();
var employeeMajor = $("#Modify_EmployeeMajor").val();
var employeeDepartment = $("#Modify_EmployeeDepartment").val();
var employeeTel = $("#Modify_EmployeeTel").val();
var employeeEmail = $("#Modify_EmployeeEmail").val();
var employeeJiGuan = $("#Modify_EmployeeJiGuan").val();
var employeeAddress = $("#Modify_EmployeeAddress").val();
var employeePosition = $("#Modify_EmployeePosition").val();
var employeeBirthday = $("#Modify_EmployeeBirthday").val();
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToUpdate",
type: "GET",
data: {
EmployeeID: employeeID, EmployeeName: employeeName, EmployeeMajor: employeeMajor,
EmployeeDepartment: employeeDepartment, EmployeeTel: employeeTel, EmployeeEmail: employeeEmail,
EmployeeJiGuan: employeeJiGuan, EmployeeAddress: employeeAddress, EmployeePosition: employeePosition,
EmployeeBirthday: employeeBirthday
},
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('编辑成功!!'); },
error: function (message) {
alert('error!');
}
});
},
"取消": function () {
$(this).dialog("close");
}
}
}); });
//查询
$("#btn_search").click(function () {
var employeeName = $("#precisionSearch_input").val();
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToSearch" + "?EmployeeName=" + employeeName,
page: ,
datatype: "json"
}).trigger("reloadGrid"); });
//导出
$("#btn_export").on("click", function () {
$("#JqGrid-table").jqGrid("exportToExcel", {
includeLabels: true,
includeGroupHeader: true,
includeFooter: true,
fileName: "jqGridExport.xlsx",
maxlength: // maxlength for visible string
});
});
//导入
$("#btn_import").click(function () {
var FileName = $("#UpLoadFile").val();
$.ajax({
url: '/JqGridDemo/ImportData/InsertDataToDB',
type: 'post',
data: { fileName: FileName }
});
});
})
</script>
</head>
<body>
<div>
<div>
<input id="UpLoadFile" type="file" />
<input id="btn_import" type="button" value="批量导入" class="btn btn-info" />
<a href="/JqGridDemo/JqGridCRUD/GetEmployeeInfoTemple">(点击此处下载模板)</a>
<label>模糊查询:</label> <input id="search_input" type="text" placeholder="模糊查询" />
<input id="precisionSearch_input" type="text" placeholder="请输入您要查询的姓名" />
<input id="btn_search" type="button" value="查询" class="btn btn-info" />
<input id="btn_add" type="button" value="添加" class="btn btn-primary" />
<input id="btn_edit" type="button" value="编辑" class="btn btn-success" />
<input id="btn_del" type="button" value="删除" class="btn btn-danger" />
<input id="btn_export" type="button" value="导出" class="btn btn-info" /> </div>
<div class="main" id="main">
<table id="JqGrid-table"></table>
<div id="JqGrid-pager"></div>
<div id="ModifyEmployeeInfo" title="修改员工信息" style="display:none;">
<table>
<tbody>
<tr>
<td>员工ID:<input type="text" id="Modify_EmployeeID" placeholder="请输入员工ID" /></td>
<td>员工姓名:<input type="text" id="Modify_EmployeeName" placeholder="请输入员工姓名" /></td>
</tr>
<tr>
<td>员工专业:<input type="text" id="Modify_EmployeeMajor" placeholder="请输入员工专业" /></td>
<td>员工部门:<input type="text" id="Modify_EmployeeDepartment" placeholder="请输入员工部门" /></td>
</tr>
<tr>
<td>员工电话:<input type="text" id="Modify_EmployeeTel" placeholder="请输入员工电话" /></td>
<td>员工邮件:<input type="text" id="Modify_EmployeeEmail" placeholder="请输入员工邮件" /></td>
</tr>
<tr>
<td>员工籍贯:<input type="text" id="Modify_EmployeeJiGuan" placeholder="请输入员工籍贯" /></td>
<td>员工住址:<input type="text" id="Modify_EmployeeAddress" placeholder="请输入员工住址" /></td>
</tr>
<tr>
<td>员工职位:<input type="text" id="Modify_EmployeePosition" placeholder="请输入员工职位" /></td>
<td>员工生日:<input type="text" id="Modify_EmployeeBirthday" placeholder="请输入员工生日" /></td>
</tr>
</tbody>
</table>
</div>
<div id="AddEmployeeInfo" title="修改员工信息" style="display:none;">
<table>
<tbody>
<tr>
<td>员工ID:<input type="text" id="ADD_EmployeeID" placeholder="请输入员工ID" /></td>
<td>员工姓名:<input type="text" id="ADD_EmployeeName" placeholder="请输入员工姓名" /></td>
</tr>
<tr>
<td>员工专业:<input type="text" id="ADD_EmployeeMajor" placeholder="请输入员工专业" /></td>
<td>员工部门:<input type="text" id="ADD_EmployeeDepartment" placeholder="请输入员工部门" /></td>
</tr>
<tr>
<td>员工电话:<input type="text" id="ADD_EmployeeTel" placeholder="请输入员工电话" /></td>
<td>员工邮件:<input type="text" id="ADD_EmployeeEmail" placeholder="请输入员工邮件" /></td>
</tr>
<tr>
<td>员工籍贯:<input type="text" id="ADD_EmployeeJiGuan" placeholder="请输入员工籍贯" /></td>
<td>员工住址:<input type="text" id="ADD_EmployeeAddress" placeholder="请输入员工住址" /></td>
</tr>
<tr>
<td>员工职位:<input type="text" id="ADD_EmployeePosition" placeholder="请输入员工职位" /></td>
<td>员工生日:<input type="text" id="ADD_EmployeeBirthday" placeholder="请输入员工生日" value="2014/03/01" /></td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#JqGrid-table").jqGrid({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
//editurl: 'clientArray',
datatype: "json",
height: ,
mtype: "Get",
colNames: ['员工ID', '员工姓名', '员工专业', '员工部门', '员工电话', '员工邮件', '员工籍贯', '员工住址', '员工职位', '员工生日'],
colModel: [{
name: 'EmployeeID',
index: 'EmployeeID',
key: true,
width: ,
edittype: Text,
editable: true,
editoptions: {
size: "",
maxlength: "",
sorttable: false,
},
searchoptions: {
searchOperMenu: false,
sopt: ['eq', 'gt', 'lt', 'ge', 'le']
}
}, {
name: 'EmployeeName',
index: 'EmployeeName',
width: ,
editable: true,
editoptions: {
size: "",
maxlength: "",
sortable: true
}
}, {
name: 'EmployeeMajor',
index: 'EmployeeMajor',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
},
{
name: 'EmployeeDepartment',
index: 'EmployeeDepartment',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeTel',
index: 'EmployeeTel',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeEmail',
index: 'EmployeeEmail',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeJiGuan',
index: 'EmployeeJiGuan',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeAddress',
index: 'EmployeeAddress',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeePosition',
index: 'EmployeePosition',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeBirthday',
index: 'EmployeeBirthday',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}],
viewrecords: true,
rowNum: ,
rowList: [, , , ],
pager: '#JqGrid-pager',
altRows: true,
multiselect: true,
multiboxonly: true,
caption: "员工信息表",
autowidth: true,
//width: "100%",
height: Audio,
sortable: true,
sortorder: 'asc',
loadonce: true, //排序时,必须添加该字段
})
//JqGrid自带的CRUD
$('#JqGrid-table').jqGrid('navGrid', "#JqGrid-pager", {
search: true, // show search button on the toolbar
add: true,
edit: true,
del: true,
refresh: true
});
//模糊查询
var timer;
$("#search_input").on("keyup", function () {
var self = this;
if (timer) { clearTimeout(timer); }
timer = setTimeout(function () {
//timer = null;
$("#JqGrid-table").jqGrid('filterInput', self.value);
}, );
});
})
</script>
</div>
</body>
</html>

6.2  分析

6.2.1  初始化数据

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

定义table获取区和翻页区

 <table id="JqGrid-table"></table>
<div id="JqGrid-pager"></div>

JqGrid

  <script type="text/javascript">
$(document).ready(function () {
$("#JqGrid-table").jqGrid({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
//editurl: 'clientArray',
datatype: "json",
height: ,
mtype: "Get",
colNames: ['员工ID', '员工姓名', '员工专业', '员工部门', '员工电话', '员工邮件', '员工籍贯', '员工住址', '员工职位', '员工生日'],
colModel: [{
name: 'EmployeeID',
index: 'EmployeeID',
key: true,
width: ,
edittype: Text,
editable: true,
editoptions: {
size: "",
maxlength: "",
sorttable: false,
},
searchoptions: {
searchOperMenu: false,
sopt: ['eq', 'gt', 'lt', 'ge', 'le']
}
}, {
name: 'EmployeeName',
index: 'EmployeeName',
width: ,
editable: true,
editoptions: {
size: "",
maxlength: "",
sortable: true
}
}, {
name: 'EmployeeMajor',
index: 'EmployeeMajor',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
},
{
name: 'EmployeeDepartment',
index: 'EmployeeDepartment',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeTel',
index: 'EmployeeTel',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeEmail',
index: 'EmployeeEmail',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeJiGuan',
index: 'EmployeeJiGuan',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeAddress',
index: 'EmployeeAddress',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeePosition',
index: 'EmployeePosition',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}, {
name: 'EmployeeBirthday',
index: 'EmployeeBirthday',
width: ,
editable: true,
//edittype: false,
editoptions: {
size: "",
maxlength: ""
}
}],
viewrecords: true,
rowNum: ,
rowList: [, , , ],
pager: '#JqGrid-pager',
altRows: true,
multiselect: true,
multiboxonly: true,
caption: "员工信息表",
autowidth: true,
//width: "100%",
height: Audio,
sortable: true,
sortorder: 'asc',
loadonce: true, //排序时,必须添加该字段
})
})
</script>

6.2.2  JqGrid自带的CRUD

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

 //JqGrid自带的CRUD
$('#JqGrid-table').jqGrid('navGrid', "#JqGrid-pager", {
search: true, // show search button on the toolbar
add: true,
edit: true,
del: true,
refresh: true
});

6.2.3 自动检测区:

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(1)功能Code

 //模糊查询
var timer;
$("#search_input").on("keyup", function () {
var self = this;
if (timer) { clearTimeout(timer); }
timer = setTimeout(function () {
//timer = null;
$("#JqGrid-table").jqGrid('filterInput', self.value);
}, );
});

6.2.4  JqGrid自带导出功能

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

$("#btn_export").on("click", function () {
$("#JqGrid-table").jqGrid("exportToExcel", {
includeLabels: true,
includeGroupHeader: true,
includeFooter: true,
fileName: "jqGridExport.xlsx",
maxlength: // maxlength for visible string
});
});

6.2.5 自定义CRUD

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

 <script type="text/javascript">
$(document).ready(function () {
//添加
$("#btn_add").click(function () {
//var model = jQuery("#JqGrid-table").jqGrid('getRowData', EmployeeID);
$("#AddEmployeeInfo").dialog({
height: ,
width: ,
resizable: false,
modal: true, //这里就是控制弹出为模态
buttons: {
"确定": function () {
//alert("在这里对数据进行修改!");
//$(this).dialog("close");
//var birthdayTime ="2017/9/28";
var employeeID = $("#ADD_EmployeeID").val();
var employeeName = $("#ADD_EmployeeName").val();
var employeeMajor = $("#ADD_EmployeeMajor").val();
var employeeDepartment = $("#ADD_EmployeeDepartment").val();
var employeeTel = $("#ADD_EmployeeTel").val();
var employeeEmail = $("#ADD_EmployeeEmail").val();
var employeeJiGuan = $("#ADD_EmployeeJiGuan").val();
var employeeAddress = $("#ADD_EmployeeAddress").val();
var employeePosition = $("#ADD_EmployeePosition").val();
var employeeBirthday = $("#ADD_EmployeeBirthday").val();
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToDdd",
type: "GET",
data: {
EmployeeID: employeeID, EmployeeName: employeeName, EmployeeMajor: employeeMajor,
EmployeeDepartment: employeeDepartment, EmployeeTel: employeeTel, EmployeeEmail: employeeEmail,
EmployeeJiGuan: employeeJiGuan, EmployeeAddress: employeeAddress, EmployeePosition: employeePosition,
EmployeeBirthday: employeeBirthday
},
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('添加数据成功'); },
error: function (message) {
alert('error!');
}
});
},
"取消": function () {
$(this).dialog("close");
}
}
});
});
//删除
$("#btn_del").click(function () {
var employeeID = $('#JqGrid-table').jqGrid('getGridParam', 'selrow');//获取行id
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToDel",
type: "post",
data: { EmployeeID: employeeID },
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('成功删除一条数据');
},
error: function (message) {
alert('error!');
}
});
});
//编辑
$("#btn_edit").click(function () {
//var ids = jQuery("#JqGrid-table").jqGrid('getDataIDs');//返回grid里所有数据的id
var id = jQuery("#JqGrid-table").jqGrid('getGridParam', 'selarrrow');
var EmployeeInfoModel = jQuery("#JqGrid-table").jqGrid('getRowData', id);
$("#Modify_EmployeeID").val(EmployeeInfoModel.EmployeeID);
$("#Modify_EmployeeName").val(EmployeeInfoModel.EmployeeName);
$("#Modify_EmployeeMajor").val(EmployeeInfoModel.EmployeeMajor);
$("#Modify_EmployeeDepartment").val(EmployeeInfoModel.EmployeeDepartment);
$("#Modify_EmployeeTel").val(EmployeeInfoModel.EmployeeTel);
$("#Modify_EmployeeEmail").val(EmployeeInfoModel.EmployeeEmail);
$("#Modify_EmployeeJiGuan").val(EmployeeInfoModel.EmployeeJiGuan);
$("#Modify_EmployeeAddress").val(EmployeeInfoModel.EmployeeAddress);
$("#Modify_EmployeePosition").val(EmployeeInfoModel.EmployeePosition);
$("#Modify_EmployeeBirthday").val(EmployeeInfoModel.EmployeeBirthday);
$("#ModifyEmployeeInfo").dialog({
height: ,
width: ,
resizable: false,
modal: true, //这里就是控制弹出为模态
buttons: {
"确定": function () {
//alert("在这里对数据进行修改!");
//$(this).dialog("close");
//var birthdayTime ="2017/9/28";
//$("#Modify_EmployeeEmployeeName").value = 'ddd';
//提交前的初始值
var employeeID = $("#Modify_EmployeeID").val();
var employeeName = $("#Modify_EmployeeName").val();
var employeeMajor = $("#Modify_EmployeeMajor").val();
var employeeDepartment = $("#Modify_EmployeeDepartment").val();
var employeeTel = $("#Modify_EmployeeTel").val();
var employeeEmail = $("#Modify_EmployeeEmail").val();
var employeeJiGuan = $("#Modify_EmployeeJiGuan").val();
var employeeAddress = $("#Modify_EmployeeAddress").val();
var employeePosition = $("#Modify_EmployeePosition").val();
var employeeBirthday = $("#Modify_EmployeeBirthday").val();
$.ajax({
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToUpdate",
type: "GET",
data: {
EmployeeID: employeeID, EmployeeName: employeeName, EmployeeMajor: employeeMajor,
EmployeeDepartment: employeeDepartment, EmployeeTel: employeeTel, EmployeeEmail: employeeEmail,
EmployeeJiGuan: employeeJiGuan, EmployeeAddress: employeeAddress, EmployeePosition: employeePosition,
EmployeeBirthday: employeeBirthday
},
success: function (message) {
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad",
page: ,
datatype: "json"
}).trigger("reloadGrid");
alert('编辑成功!!'); },
error: function (message) {
alert('error!');
}
});
},
"取消": function () {
$(this).dialog("close");
$("#JqGrid-table").jqGrid('clearGridData');
//$("#JqGrid-table").trigger('reloadGrid');
$("#JqGrid-table").setGridParam({ url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToLoad" }).trigger('reloadGrid');
}
}
}); });
//查询
$("#btn_search").click(function () {
var employeeName = $("#precisionSearch_input").val();
$("#JqGrid-table").jqGrid("setGridParam",
{
url: "/JqGridDemo/JqGridCRUD/EmployeeInfoToSearch" + "?EmployeeName=" + employeeName,
page: ,
datatype: "json"
}).trigger("reloadGrid"); });
//导出
$("#btn_export").on("click", function () {
$("#JqGrid-table").jqGrid("exportToExcel", {
includeLabels: true,
includeGroupHeader: true,
includeFooter: true,
fileName: "jqGridExport.xlsx",
maxlength: // maxlength for visible string
});
});
//导入
$("#btn_import").click(function () {
var FileName = $("#UpLoadFile").val();
$.ajax({
url: '/JqGridDemo/ImportData/InsertDataToDB',
type: 'post',
data: { fileName: FileName }
});
});
})
</script>

6.2.6 导出

(1)图解功能

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

(2)功能Code

 using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MVCCrud.Areas.JqGridDemo.Controllers
{
public class ImportDataController : Controller
{
// GET: JqGridDemo/ImportData
public ActionResult Index()
{
return View();
} /// <summary>
/// 从excel读取数据
/// </summary>
/// <param name="filepath">excel文件路径</param>
/// <returns></returns>
public static DataSet ReadExcel(string FilePath)
{
try
{
string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", FilePath);
using (OleDbConnection OleDbConn = new OleDbConnection(strConn))
{
OleDbConn.Open();
string sql = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter OleDbDA = new OleDbDataAdapter(sql, OleDbConn);
DataSet OleDS = new DataSet();
OleDbDA.Fill(OleDS, "ExcelToTalbe");
return OleDS;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// 将excel数据插入到EmployeeName表中
/// </summary>
/// <param name="fileName">excel文件所在路径</param>
public void InsertDataToDB(string fileName)
{
//fileName = @"E:\testData.xls";
if (!System.IO.File.Exists(fileName))
{
throw new Exception("指定路径的Excel文件不存在!");
}
DataSet ds = ReadExcel(fileName);
List<string> ListData = (from DataRow row in ds.Tables["ExcelToTalbe"].Rows select String.Format("INSERT INTO EmployeeInfo(EmployeeID,EmployeeName,EmployeeMajor,EmployeeDepartment,EmployeeTel,EmployeeEmail, EmployeeJiGuan,EmployeeAddress,EmployeePosition,EmployeeBirthday) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')", row[], row[], row[], row[], row[], row[], row[], row[], row[], row[])).ToList();
string ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
foreach (string item in ListData)
{
SqlCommand comn = new SqlCommand(item, conn);
comn.ExecuteNonQuery();
}
}
}
}

7   问题区

Q1:批量导入时,excel版本问题

Q2:批量导入时,input 上传文件路径,需要使用相对路径,而非绝对路劲

8   待解决问题

Q1:统一异常控制

Q2:JqGrid换肤

Q3:压力测试

Q4:友好提示

Q4:其他

9   最后

首先祝福大家国庆快乐,除此之外,若有任何问题,欢迎指教。

10   参考文献

[01]http://www.trirand.com/blog/?page_id=5

[02]http://blog.mn886.net/jqGrid/

11  服务区

有喜欢的朋友,可以看一下,不喜欢的的朋友,勿喷,谢谢!!

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查

12  版权

  • 感谢您的阅读,若有不足之处,欢迎指教,共同学习、共同进步。
  • 博主网址:http://www.cnblogs.com/wangjiming/。
  • 极少部分文章利用读书、参考、引用、抄袭、复制和粘贴等多种方式整合而成的,大部分为原创。
  • 如您喜欢,麻烦推荐一下;如您有新想法,欢迎提出,邮箱:2098469527@qq.com。
  • 可以转载该博客,但必须著名博客来源。

【ASP.NET MVC系列】浅谈jqGrid 在ASP.NET MVC中增删改查的更多相关文章

  1. ASP&period;NET CORE系列【二】使用Entity Framework Core进行增删改查

    介绍 EntityFrameworkCore EF core 是一个轻量级的,可扩展的EF的跨平台版本.对于EF而言 EF core 包含许多提升和新特性,同时 EF core 是一个全新的代码库,并 ...

  2. ASP&period;NET CORE系列【三】使用Entity Framework Core进行增删改查

    身份验证 以前我们熟悉的web.config中配置的form验证,现在没有了.我们来看看在Core里面如何配置: 首先需要NuGet安装一个包:Microsoft.AspNetCore.Authent ...

  3. 国产化之路-统信UOS &plus; Nginx &plus; Asp&period;Net MVC &plus; EF Core 3&period;1 &plus; 达梦DM8实现简单增删改查操作

    专题目录 国产化之路-统信UOS操作系统安装 国产化之路-国产操作系统安装.net core 3.1 sdk 国产化之路-安装WEB服务器 国产化之路-安装达梦DM8数据库 国产化之路-统信UOS + ...

  4. ASP&period;NET Identity系列02,在ASP&period;NET MVC中增删改查用户

    本篇体验在ASP.NET MVC中使用ASP.NET Identity增删改查用户. 源码在这里:https://github.com/darrenji/UseIdentityCRUDUserInMV ...

  5. 大数据系列之分布式数据库HBase-0&period;9&period;8安装及增删改查实践

    若查看HBase-1.2.4版本内容及demo代码详见 大数据系列之分布式数据库HBase-1.2.4+Zookeeper 安装及增删改查实践 1. 环境准备: 1.需要在Hadoop启动正常情况下安 ...

  6. MVC模式下如何对多选框数据进行增删改查

    一.业务情景:      做的是一个项目管理的增删改查模块,一个项目里面有项目成员属性,而且一个项目可以有多个成员,一个成员可以参加多个项目,多对多关系,数据库表里自然要建立一个关系表. 视图 二.视 ...

  7. 基于MVC和Bootstrap的权限框架解决方案 二.添加增删改查按钮

    上一期我们已经搭建了框架并且加入了列表的显示, 本期我们来加入增删改查按钮 整体效果如下 HTML部分,在HTML中找到中意的按钮按查看元素,复制HTML代码放入工程中 <a class=&qu ...

  8. 【ASP&period;NET MVC】jqGrid 增删改查详解

    1   概述 本篇文章主要是关于JqGrid的,主要功能包括使用JqGrid增删查改,导入导出,废话不多说,直接进入正题. 2   Demo相关 2.1   Demo展示 第一部分 第二部分 2.2 ...

  9. JS组件系列——BootstrapTable&plus;KnockoutJS实现增删改查解决方案(四):自定义T4模板快速生成页面

    前言:上篇介绍了下ko增删改查的封装,确实节省了大量的js代码.博主是一个喜欢偷懒的人,总觉得这些基础的增删改查效果能不能通过一个什么工具直接生成页面效果,啥代码都不用写了,那该多爽.于是研究了下T4 ...

随机推荐

  1. 百度在线笔试编程测试题&lpar;Python&rpar;:整数分解成素数的积

    编程测试题: 输入一个正整数将其分解成素数的乘积,输入格式连续输入m个数,然后将这m个数分别分解,如 输入: 2 10 20 输出: 2 5 2 2 5 Python code: def primes ...

  2. 2016 Multi-University Training Contest 2 第一题Acperience

    Acperience Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Probl ...

  3. 修改weblogic11g的JDK版本

    1:进入Weblogic域文件夹下面 [wzh@localhost bin]$ pwd/app/wzh/oracle/middleware/user_projects/domains/base_dom ...

  4. bzoj2809

    可以先穷举那个是管理者,然后就发现其实就是求每个子树选尽可能多的人,使薪水和小于m这显然是从小往大选,可以用启发式合并但是用主席树写的更简单一点吧,dfs序之后每课线段树不仅维护出现出现个数,然后在维 ...

  5. php笔记&lpar;八&rpar;PHP类与对象之抽象类

    <?php //通过abstract关键字定义一个抽象类 abstract class ACanEat{ //通过abstract关键字定一个不用具体实现的抽象方法eat() abstract ...

  6. 【LeetCode】89&period; Gray Code

    题目: The gray code is a binary numeral system where two successive values differ in only one bit. Giv ...

  7. R语言︱LDA主题模型——最优主题&period;&period;&period;

    R语言︱LDA主题模型——最优主题...:https://blog.csdn.net/sinat_26917383/article/details/51547298#comments

  8. fs项目----&gt&semi;async&sol;await的学习(一)

    2018-07-11号,我来到了fs项目组担任后端开发的角色.这是我来thoughtworks以来首个的正式项目,不管是在技术还是在敏捷的实践中都是受益匪浅.来感受tw特殊的文化的同时,我希望自己能够 ...

  9. mac下配置android环境变量

    下面我将一下mac环境下的配置步骤: 1.在本地目录(home directory)中创建文件.bash_profile2.在文件中写入以下内容:export PATH=${PATH}:/Users/ ...

  10. 由于更换硬盘没有删除系统自启动读取挂载硬盘导致系统报错&colon;fsck&period;ext4 unable to resolve &&num;39&semi;UUID&equals;a4a7a0f7-b54f-4774-9fb1&&num;39&semi;

    由于更换硬盘没有删除系统自启动读取挂载硬盘导致系统报错:fsck.ext4 unable to resolve 'UUID=a4a7a0f7-b54f-4774-9fb1' 此时进入系统已root模式 ...