How to Bind Data in Webgrid usig PartialView in ASP.net MVC - c#

Iam new to .Net MVC. I need to bind data into webgrid return using PartialView(),or
If it is possible to return back using JSON,Now My code will execute on Dropdown change,But it will not bind values in web grid.
JavaScript,Model,Controller Codes are shown below:
Script
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
$.post('#Url.Action("SelectCustomerByID", "Admin")', {secondValue:firstDDLValue }, function (ReceiptList) {
alert(firstDDLValue);
$('#divgrid').html(ReceiptLists);
});
});
});
</script>
View:
<div id="divgrid" style="margin-top: 15px;">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
#grid.GetHtml(
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns: grid.Columns(
grid.Column("Id", "ID", style: "id"),
grid.Column("Cust_Name", "Cust Name", style: "PName"),
grid.Column("Pay_Amount", "Pay_Amount", style: "ICode"),
grid.Column("Pay_Mode", "Pay_Mode", style: "IName"),
grid.Column("Bank_Name", "Bank_Name", style: "Weight"),
grid.Column("Bank_Address", " Bank_Address", style: "MakingCharge"),
grid.Column("ChequeNo", "ChequeNo", style: "Certification"),
grid.Column("Cheque_Date", " Cheque_Date", style: "Price"),
grid.Column("Date", "Date", style: "Price"),
grid.Column("Edit", "", #<a href='../Admin/EditReceipt?id=#item.ID' ><img src="~/Images/edit.png" alt='Edit' /></a>, style: "width:10%"),
grid.Column(header: "Delete", format: #<text><img src="../Images/delete.png" alt='Delete' /></text>) ))
#if (grid.HasSelection)
{
Receipt = (JewellaryWeb.Models.Receipt)grid.Rows[grid.SelectedIndex].Value;
<b>Id</b> #Receipt.Id<br />
<b>Name</b> #Receipt.Cust_Name<br />
<b>Amount</b> #Receipt.Pay_Amount<br />
<b>PayMode</b> #Receipt.Pay_Mode<br />
<b>BankName</b> #Receipt.Bank_Name<br />
<b>BankAddress</b> #Receipt.Bank_Address<br />
<b>ChequeNumber</b> #Receipt.ChequeNo<br />
<b>ChequeDate</b> #Receipt.Cheque_Date<br />
}
</div>
Controller:
public ActionResult SelectCustomerByID(Receipt model,string secondValue)
{
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
Receipt Receipt = new Models.Receipt();
model.ReceiptList = Receipt.GetReceiptListByCustID(CustID);
return PartialView(model.ReceiptList);
}

I found answer for this I just modified my Script and Use ParitalView to bind data in gird My Solution Code is:
Script
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
$.get('#Url.Action("SelectCustomerByID", "Admin")', { secondValue: firstDDLValue }, function (ReceiptList) {
$('#gridContent').html(ReceiptList);
});
});
});
</script>
i create new _Recepitgrid.cshtml as PartialView and write the code for Webgrid as Same as in the main view.
Controller
public ActionResult SelectCustomerByID(Receipt model, string secondValue)
{
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
Receipt Receipt = new Models.Receipt();
ReceiptList = Receipt.GetReceiptListByCustID(CustID);
return PartialView("_Recepitgrid", ReceiptList);
}
Now it will works fine..

Related

jqGrid is not reloading or refreshing properly on keyup event

I needed to create a search page where various types of text, dropdown, date field will be there. i added onkeyup function to every text field so that whenever i put any text or number a grid will appear with subgrid. The issue i am facing is if i give input for the first time then the grid appear with correct data. if i clear that field then the grid is reloading also but if i input again in that field or any other text field then the js is not sending request to the action method with updated post value.
Here is my View Part:
<section class="content">
<div class="container-fluid">
<!-- SELECT2 EXAMPLE -->
<!-- SELECT2 EXAMPLE -->
<div class="card card-info">
<div class="card-header">
<h3 class="card-title">Search Criteria</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse">
<i class="fas fa-minus"></i>
</button>
</div>
</div>
<!-- /.card-header -->
#using (Html.BeginForm("SearchReport", "LRLiveSearch", FormMethod.Post))
{
<div class="card-body">
<div class="row">
<div class="col-md-12" style="line-height:1.50px;">
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label>Deed No</label>
#Html.TextBoxFor(model => model.DeedNo, new { #class = "form-control", onkeyup = "LiveSearch('DN', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Deed Identity</label>
#Html.TextBoxFor(model => model.DeedId, new { #class = "form-control", onkeyup = "LiveSearch('DI', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Client Name</label>
#Html.TextBoxFor(model => model.ClientName, new { #class = "form-control", onkeyup = "LiveSearch('CN', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Client Contact Number</label>
#Html.TextBoxFor(model => model.ClientPhoneNumber, new { #class = "form-control", onkeyup = "LiveSearch('CP', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>MR No</label>
#Html.TextBoxFor(model => model.MRNo, new { #class = "form-control", onkeyup = "LiveSearch('MR', this.value)" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Cheque No</label>
#Html.TextBoxFor(model => model.ChequeNo, new { #class = "form-control", onkeyup = "LiveSearch('CQN', this.value)" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label>Collection Type</label>
#Html.DropDownListFor(model => model.CollectionType, Model.CollectionTypeList, new { #class = "form-control" })
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>From Date</label>
<div class="input-group date" id="FirstDate" data-target-input="nearest">
#Html.TextBoxFor(model => model.FromDate, new { #class = "form-control datetimepicker-input", #data_target = "#FirstDate" })
<div class="input-group-append" data-target="#FirstDate" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>To Date</label>
<div class="input-group date" id="SecondDate" data-target-input="nearest">
#Html.TextBoxFor(model => model.ToDate, new { #class = "form-control datetimepicker-input", #data_target = "#SecondDate" })
<div class="input-group-append" data-target="#SecondDate" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
</div>
#*<div class="col-md-1">
<div class="form-group">
<center>
<button id="btnLRSearch" formaction="SearchList" class="btn btn-md btn-primary" style="margin-top:.80rem" type="button">Search</button>
</center>
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<center>
<button id="btnPrint" formaction="SearchReport" class="btn btn-md btn-warning" style="margin-top:.80rem" type="submit">Report</button>
</center>
</div>
</div>*#
</div>
</div>
</div>
</div>
}
</div>
</div>
<!-- /.container-fluid -->
<table class="table table-bordered table-striped table-hover text-nowrap text-sm" id="Demogrid"></table>
<div class="container-fluid" id="pager"></div>
</section>
here is my JS part where i handled onkeyup event:
function LiveSearch(type, value) {
var searchType = type;
var searchValue = value;
if (value == "" || value == null) {
$("#Demogrid").jqGrid('setGridParam', { postData: { Type: searchType, SearchValue: searchValue } }).trigger('reloadGrid');
return true;
}
else {
$("#Demogrid").jqGrid({
url: '/HRM/LRLiveSearch/LiveSearch',
datatype: "json",
mtype: 'Get',
//table header name
colNames: ['ProjectName', 'PlotName', 'TotalLandArea', 'DeedId', 'DeedDate', 'RentFeeType', 'RentFee', 'ClientName', 'ClientAddress', 'ClientContactNo', 'EffectiveDate'],
//colModel takes the data from controller and binds to grid
colModel: [
{ name: "ProjectName" },
{ name: "PlotName" },
{ name: "TotalLandArea" },
{ name: "DeedId" },
{ name: "DeedDate" },
{ name: "RentFeeType" },
{ name: "RentFee" },
{ name: "ClientName" },
{ name: "ClientAddress" },
{ name: "ClientContactNo" },
{ name: "EffectiveDate" }
],
height: '100%',
viewrecords: true,
caption: 'Deed Info',
emptyrecords: 'No records',
rowNum: 10,
pager: jQuery('#pager'),
rowList: [10, 20, 30, 40],
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
postData: {
Type: searchType,
SearchValue: searchValue
},
autowidth: true,
subGrid: true,
subGridRowExpanded: function (subgridId, rowId) {
// create the subgrid HTML here
var subgridTableId = subgridId + "_t";
$("#" + subgridId).html("<table id='" + subgridTableId + "'></table>");
// get the data for the parent row
var parentRowData = $("#Demogrid").jqGrid("getRowData", rowId);
// retrieve the primary key value of the parent row
var parentId = parentRowData.DeedId;
$("#" + subgridTableId).jqGrid({
// configure the subgrid
url: '/HRM/LRLiveSearch/LiveSearch',
datatype: "json",
mtype: 'Get',
//table header name
colNames: ['CollectionId', 'CollectionDate', 'MRIdentity', 'MRNo', 'MRDate', 'MRType', 'CollectionType', 'ChequeNo', 'BankName'],
//colModel takes the data from controller and binds to grid
colModel: [
{ name: "CollectionId", hidden: true },
{ name: "CollectionDate" },
{ name: "MRIdentity" },
{ name: "MRNo" },
{ name: "MRDate" },
{ name: "MRType" },
{ name: "CollectionType" },
{ name: "ChequeNo" },
{ name: "BankName" }
],
height: '100%',
viewrecords: true,
caption: 'Collection Details',
emptyrecords: 'No records',
rowNum: 10,
jsonReader: {
repeatitems: false
},
postData: {
Type: searchType,
SearchValue: searchValue,
DeedId: parentId
},
autowidth: true
});
},
}).navGrid('#pager',
{
edit: true,
add: true,
del: true,
search: true,
refresh: true,
closeAfterSearch: true
});
}
}
and it is my action method:
public JsonResult LiveSearch(string sord, int page, int rows, string searchString, string Type, string SearchValue, string DeedId)
{
if(SearchValue == "")
{
SearchValue = "$";
}
var query = iLRSearchRepository.LiveSearchFilter(Type, SearchValue);
if (DeedId == null)
{
//#2 Setting Paging
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
//#3 Linq Query to Get Data
var Results = query.Select(
x => new
{
ProjectName = x.ProjectName,
PlotName = x.PlotName,
TotalLandArea = x.TotalLandArea,
DeedId = x.DeedId,
DeedDate = x.DeedDate.ToString("dd/MM/yyyy"),
RentFeeType = x.RentFeeType,
RentFee = x.RentFee,
ClientName = x.ClientName,
ClientAddress = x.ClientsAddress,
ClientContactNo = x.ClientsContactNo,
EffectiveDate = x.ActivateDate.ToString("dd/MM/yyyy")
}).Distinct();
//#4 Get Total Row Count
int totalRecords = Results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
//#5 Setting Sorting
if (sord.ToUpper() == "DESC")
{
Results = Results.OrderByDescending(s => s.DeedId);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
Results = Results.OrderBy(s => s.DeedId);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
//#6 Setting Search
if (!string.IsNullOrEmpty(searchString))
{
Results = Results.Where(m => m.DeedId == searchString);
}
//#7 Sending Json Object to View.
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
else
{
var Results = query.Where(x => x.DeedId == DeedId).Select(
x => new
{
CollectionId = x.CollectionId,
CollectionDate = x.CollectionDate?.ToString("dd/MM/yyyy"),
MRIdentity = x.MRIdentity,
MRNo = x.MRNo,
MRDate = x.MRDate?.ToString("dd/MM/yyyy"),
MRType = x.MRType,
CollectionType = x.CollectionType,
ChequeNo = x.ChequeNo,
BankName = x.BankName,
});
var jsonData = new
{
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
//model.landRent_View_SearchInfos = query;
//return View("_LandRentInfoList", model);
}
With your code you every time try create jqGrid when you do a search, which of course is not allowed since the grid is already created.
if (value == "" || value == null) {
$("#Demogrid").jqGrid('setGridParam', { postData: { Type: searchType, SearchValue: searchValue } }).trigger('reloadGrid');
return true;
}
else {
$("#Demogrid").jqGrid({}...)
}
To solve the problem first create the grid and the do a reload when the value changes
$("#Demogrid").jqGrid({
url: '/HRM/LRLiveSearch/LiveSearch',
datatype: "json",
mtype: 'Get',
//table header name
...
});
function LiveSearch(type, value) {
var searchType = type;
var searchValue = value;
$("#Demogrid").jqGrid('setGridParam', { postData: { Type: searchType, SearchValue: searchValue } }).trigger('reloadGrid');
return true;
}
Hope this helps.
Initially you can set values (postData) so that the grid return empty data or create the grid with empty local data (datatype : local) and then change the datatype to json.

Paging in webgrid not working in asp.net mvc 5

I have following view and controller. Problem is that when enabling paging and I click on next page, previous view is gone
#using System
#using System.Web.Helpers
#*#model List<DataTransferObjects.UserClaimHistory>*#
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="~/Content/style.css" rel="stylesheet" type="text/css" />
#*<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>*#
<script src="~/Scripts/jquery-1.7.1.js"></script>
<style>
/*Here I will write some css for looks good*/
th, td {
padding: 5px;
}
th {
background-color: gray;
}
</style>
</head>
#{
ViewBag.Title = "ViewReports";
var grid = new WebGrid(Model, canPage: false, rowsPerPage: 2, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent", canSort: false);
}
#{
var fromDateVal = (DateTime)ViewBag.fromDate;
var toDateVal = (DateTime)ViewBag.toDate;
}
#using (Html.BeginForm("Index", "ViewReport", FormMethod.Post))
{
<div class="container">
#{
var homeHeader = Html.Partial("_HomeHeader");
}
#homeHeader
<div id="logout-div">
#Html.ActionLink("Log Out", "Logout", "Home", null, null )
</div>
#{
var homeLeftPanel = Html.Partial("_HomeLeftPanel");
}
#homeLeftPanel
<div>
From Date: #Html.TextBox("fromDate", string.Format("{0:yyyy-MM-dd}", fromDateVal), new { #id = "fromDate", #class = "datefield", type = "date" })
To Date: #Html.TextBox("toDate", string.Format("{0:yyyy-MM-dd}", toDateVal), new { #id = "toDate", #class = "datefield", type = "date" })
<input type="submit" value="Search" />
</div>
<div id="main" style="padding: 25px;">
#grid.GetHtml(
htmlAttributes: new { id = "MainGrid", width = "60%" },
tableStyle: "table table-bordered table-responsive",
headerStyle: "header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("UserName", "User Name"),
grid.Column("Email", "Email"),
grid.Column("Claim", "Accessed"),
grid.Column(header: "AccessedOn", format: (item) => string.Format("{0:dd-MM-yyyy}", item.AccessedOn)),
grid.Column(format: (item) =>
{
if (item.Count > 1)
{
var subGrid = new WebGrid(source: item.List, canSort: false);
return subGrid.GetHtml(displayHeader: true,
htmlAttributes: new { id = "SubGrid", width = "100%" },
columns: subGrid.Columns(
subGrid.Column("UserName", "User Name"),
subGrid.Column("Email", "Email"),
subGrid.Column("Claim", "Accessed"),
subGrid.Column("AccessedOn", "AccessedOn")
)
);
}
else
{
return null;
}
})
)
)
<script>
$(document).ready(function () {
var size = $("#main #MainGrid > thead > tr > th").size(); // get total column
$("#main #MainGrid > thead > tr > th").last().remove(); // remove last column
$("#main #MainGrid > thead > tr").prepend("<th></th>"); // add one column at first for collapsible column
$("#main #MainGrid > tbody > tr").each(function (i, el) {
$(this).prepend(
$("<td></td>")
.addClass("expand")
.addClass("hoverEff")
.attr('title', "click for show/hide")
);
//Now get sub table from last column and add this to the next new added row
var table = $("table", this).parent().html();
//
// alert(table);
//add new row with this subtable
// ADD CLICK EVENT FOR MAKE COLLAPSIBLE
if (table !== null) {
$(this).after("<tr><td></td><td style='padding:5px; margin:0px;' colspan='" + (size - 1) + "'>" + table + "</td></tr>");
$("table", this).parent().remove();
$(".hoverEff", this).live("click", function () {
$(this).parent().closest("tr").next().slideToggle(100);
$(this).toggleClass("expand collapse");
});
} else {
$(this).find('td:eq(0)').removeClass();
}
});
//by default make all subgrid in collapse mode
$("#main #MainGrid > tbody > tr td.expand").each(function (i, el) {
$(this).toggleClass("expand collapse");
$(this).parent().closest("tr").next().slideToggle(100);
});
});
</script>
</div>
#if (ViewBag.Count > 0)
{
<div>
#Html.ActionLink("Export", "ExportToExcel", "ViewReport", new { fromDate = fromDateVal, toDate = toDateVal}, null)
</div>
}
#{
var homeFooter = Html.Partial("_HomeFooter");
}
#homeFooter
</div>
}
</html>
And this is the controller:
public ActionResult Index(DateTime? fromDate, DateTime? toDate)
{
if (!fromDate.HasValue)
fromDate = DateTime.Now.Date;
if (!toDate.HasValue)
toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
if (toDate < fromDate)
toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
ViewBag.fromDate = fromDate;
ViewBag.toDate = toDate;
var userClaims = DbAccessWebApiHandler.GetUserClaimAccesshistory(new DateSelection
{
StartDate = fromDate.Value,
EndDate = toDate.Value
});
if (userClaims != null)
{
ViewBag.Count = userClaims.Count;
var newList = userClaims.GroupBy(x => new { x.UserName, x.Email, x.Claim, x.AccessedOn.Date })
.Select(y => new UserClaimHistoryGroup
{
UserName = y.Key.UserName,
Email = y.Key.Email,
Claim = y.Key.Claim,
AccessedOn = y.Key.Date,
List = y.ToList(),
Count = y.ToList().Count
});
return View(newList);
}
userClaims = new List<UserClaimHistory>();
return View(userClaims);
}
[System.Web.Mvc.HttpGet]
public ActionResult ExportToExcel(DateTime? fromDate, DateTime? toDate)
{
if (!fromDate.HasValue)
fromDate = DateTime.Now.Date;
if (!toDate.HasValue)
toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
if (toDate < fromDate)
toDate = fromDate.GetValueOrDefault(DateTime.Now.Date).Date.AddDays(1);
ViewBag.fromDate = fromDate;
ViewBag.toDate = toDate;
var userClaims = DbAccessWebApiHandler.GetUserClaimAccesshistory(new DateSelection
{
StartDate = fromDate.Value,
EndDate = toDate.Value
});
if (userClaims != null)
{
var gv = new GridView();
gv.AutoGenerateColumns = false;
gv.Columns.Add(new BoundField { HeaderText = "UserName", DataField = "UserName" });
gv.Columns.Add(new BoundField { HeaderText = "Email", DataField = "Email" });
gv.Columns.Add(new BoundField { HeaderText = "Accessed", DataField = "Claim" });
gv.Columns.Add(new BoundField { HeaderText = "Date", DataField = "AccessedOn" });
var dt = new DataTable();
dt.Columns.Add("UserName");
dt.Columns.Add("Email");
dt.Columns.Add("Claim");
dt.Columns.Add("AccessedOn");
foreach (var item in userClaims)
{
dt.Rows.Add(item.UserName, item.Email, item.Claim, item.AccessedOn);
}
gv.DataSource = dt;
gv.DataBind();
for (var i = 0; i < userClaims.Count; i++)
{
gv.Rows[i].Height = 40;
}
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Reports.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
var sw = new StringWriter();
var htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
return View("Index");
}
Have able to work via following script
var links = $('a[href*=page], a[href*=sort]'), form = $('form');
links.click(function () {
form.attr("action", this.href);
$(this).attr("href","javascript:");
form.submit();
});
as mentioned in How do I get my WebGrid to POST instead of GET during a sort or paging operation in my MVC4 site?

Context menu within WebGrid

I am using WebGrid in my MVC project and I want to add a context menu on right click (on row click) in that WebGrid. So, could anyone please help me how to add a context menu in my webgrid and on selection of a context menu item, how to retrieve the id? Following is the code of more detail:
#using (Html.BeginForm("save", "Inventory"))
{
var grid = new WebGrid(Model.products, canSort: false, canPage: true, rowsPerPage: 3);
int rowNum = 0;
<div>
#grid.GetHtml(tableStyle: "webGrid", alternatingRowStyle: "alt", headerStyle: "header",
selectedRowStyle: "select",
columns: grid.Columns
(
grid.Column("RowNumber", format: item => rowNum = rowNum + 1, style: "rowno"),
grid.Column("Id",
format: (item) => Html.TextBox("products[" + (rowNum - 1).ToString() + "].Id",
(object)item.Id, new { #readonly = "readonly" }),
style: "id"),
grid.Column("Name", format: (item) => Html.TextBox("products[" + (rowNum - 1).ToString() + "].Name", (object)item.Id), style:"name"),
grid.Column("Description", format: (item) => Html.TextBox("products[" + (rowNum - 1).ToString() + "].Description", (object)item.Description), style: "desc"),
grid.Column("Quantity", format: (item) => Html.TextBox("products[" + (rowNum - 1).ToString() + "].Quantity", (object)item.Quantity), style: "qty"),
grid.Column("QualityType", format: #item => Html.DropDownList("products[" + (rowNum - 1).ToString() + "].QualityType", (IEnumerable<SelectListItem>)Model.products[rowNum - 1].QualityTypeModel), style: "qlty")
), mode: WebGridPagerModes.Numeric)
</div>
<input type="submit" value="Submit">
}
Recently I implemented a similar task, using jQuery Context Menu.
Here is the result
#{
#model IEnumerable<TestWebGirdContextMenu.Models.User>
}
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.4.3/jquery.contextMenu.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.4.3/jquery.contextMenu.min.js" type="text/javascript"></script>
<div class="container">
<h2>WebGrid Context Menu</h2>
<div class="row">
<div class="col-lg-12">
#{
var grid = new WebGrid(Model);
}
#grid.GetHtml(htmlAttributes: new { id = "webGrid" })
</div>
</div>
</div>
<script>
$(function () {
$.contextMenu({
selector: "#webGrid tbody tr",
callback: function (key, options) {
var m = "clicked: " + key;
window.console && console.log(m) || alert(m);
},
items: {
"edit": { name: "Edit", icon: "edit" },
"cut": { name: "Cut", icon: "cut" },
"copy": { name: "Copy", icon: "copy" },
"paste": { name: "Paste", icon: "paste" },
"delete": { name: "Delete", icon: "delete" },
"sep1": "---------",
"quit": {
name: "Quit", icon: function () {
return 'context-menu-icon context-menu-icon-quit';
}
}
}
});
$('.context-menu-one').on('click', function (e) {
console.log('clicked', this);
});
});
</script>
</body>
Demo jQuery Context Menu

How to Bind JSON return result value in webgird on ASP.net MVC4

I want to bind Datatable values in webgrid using Json. I used DropDownlist to select Name of person dependent on those names i want to bind it in webgrid.Now i used some codes but unable t bind data in grid.
My Code Is:
View
<div id="divgrid" style="margin-top: 15px;">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.NextPrevious);}
<div id="gridContent">
#grid.GetHtml(
tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
columns: grid.Columns(
grid.Column("Id", "ID", style: "id"),
grid.Column("Cust_Name", "Cust Name", style: "PName"),
grid.Column("Pay_Amount", "Pay_Amount", style: "ICode"),
grid.Column("Pay_Mode", "Pay_Mode", style: "IName"),
grid.Column("Bank_Name", "Bank_Name", style: "Weight"),
grid.Column("Bank_Address", " Bank_Address", style: "MakingCharge"),
grid.Column("ChequeNo", "ChequeNo", style: "Certification"),
grid.Column("Cheque_Date", " Cheque_Date", style: "Price"),
//grid.Column("Cheque_Date", "Cheque_Date", format: item => ((item.Cheque_Date == null) ? "" : item.Cheque_Date.ToString("dd/MM/yyyy")), style: "name"),
grid.Column("Date", "Date", style: "Price"),
grid.Column("Edit", "", #<a href='../Admin/EditReceipt?id=#item.ID' ><img src="~/Images/edit.png" alt='Edit' /></a>, style: "width:10%"),
grid.Column(header: "Delete", format: #<text><img src="../Images/delete.png" alt='Delete' /></text>)
))
#if (grid.HasSelection)
{
Receipt = (JewellaryWeb.Models.Receipt)grid.Rows[grid.SelectedIndex].Value;
<b>Id</b> #Receipt.Id<br />
<b>Name</b> #Receipt.Cust_Name<br />
<b>Amount</b> #Receipt.Pay_Amount<br />
<b>PayMode</b> #Receipt.Pay_Mode<br />
<b>BankName</b> #Receipt.Bank_Name<br />
<b>BankAddress</b> #Receipt.Bank_Address<br />
<b>ChequeNumber</b> #Receipt.ChequeNo<br />
<b>ChequeDate</b> #Receipt.Cheque_Date<br />
}
</div>
Script:
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
// alert(firstDDLValue);
$.post('#Url.Action("SelectCustomerByID", "Admin")', { secondValue: firstDDLValue }, function (ReceiptList) {
alert(firstDDLValue);
var grdPipeline = $find("#grid");
grdPipeline.set_dataSource(ReceiptList);
grdPipeline._pi.show(grdPipeline);
grdPipeline.applyClientBinding();
grdPipeline._pi.hide(grdPipeline);
alert(firstDDLValue);
$("#ItemName").text(Data);
});
});
});
</script>
Control:
public JsonResult SelectCustomerByID(string secondValue)
{
Receipt Recepit = new Receipt();
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
ReceiptList = Recepit.GetReceiptListByCustID(CustID);
return Json(ReceiptList, JsonRequestBehavior.AllowGet);
}
Model:
public ObservableCollection<Receipt> GetReceiptListByCustID(int CustID)
{
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
DataTable dtReceipt = new DataTable();
DbParameter[] objParams = new DbParameter[1];
objParams[0] = objDAL.CreateParameter("#REC_Cust_ID", DbType.Int32, CustID);
dtReceipt = objDAL.ExecuteTable(CommandType.StoredProcedure, "[sp_Receipt_Select_ByCustID]",objParams);
foreach (DataRow dr in dtReceipt.Rows)
{
ReceiptList.Add(new Receipt
{
Id = Convert.ToInt32(dr["REC_Id_I"]),
Cust_Name = dr["CUS_Name_V"].ToString(),
Pay_Amount = dr["REC_PaidAmount_M"].ToString(),
Pay_Mode = dr["REC_PayMode_C"].ToString(),
Bank_Name = dr["REC_BankName_V"].ToString(),
Bank_Address = dr["REC_BankAddress"].ToString(),
ChequeNo = dr["REC_ChequeNo_V"].ToString(),
Cheque_Date = dr["REC_ChequeDate_D"].ToString(),
Date = Convert.ToDateTime(dr["REC_Date_D"].ToString()),
});
}
return ReceiptList;
}
You can Use PartialView to bind Data in Web grid, I used this code:
Script:
<script type="text/javascript">
$(document).ready(function () {
$("#Cust_Id").change(function () {
firstDDLValue = $("#Cust_Id").val();
$.get('#Url.Action("SelectCustomerByID", "Admin")', { secondValue: firstDDLValue }, function (ReceiptList) {
$('#gridContent').html(ReceiptList);
});
});
});
</script>
Controller:
`public ActionResult SelectCustomerByID(Receipt model, string secondValue)
{
//Receipt Recepit = new Receipt();
int CustID = 0;
if (secondValue != "")
CustID = Convert.ToInt32(secondValue);
ObservableCollection<Receipt> ReceiptList = new ObservableCollection<Receipt>();
Receipt Receipt = new Models.Receipt();
if(CustID!=0)
ReceiptList = Receipt.GetReceiptListByCustID(CustID);
else
ReceiptList = Receipt.GetReceiptList();
ViewData["Count"] = ReceiptList.Count;
return PartialView("_Recepitgrid", ReceiptList);
}

Jqgrid Master Detail Submit Form using ViewModel Classes

I have a asp.net MVC View Page which is Master/Detail style.
After reading from this , I realize that I need to serialize jqgrid data before I send to Controller Layer.
[HttpPost]
public ActionResult Detail(Seminar Seminar, List<Seminar_Detail> Seminar_Details)
{
}
So my question is,
1. How could i send data to controller, by using 2 ViewModel classes.
SeminarMaster for Form Input Fields and SeminarDetail for Jqgrid entire rows.
2.If you say, I have only one way which is serializing to jqgrid, then Do i need to serialize Form input fields also?
3.If I have to use serialize way, Do I have chance to use ViewModel classess to parse data to Controller Layer ?
Updated
JqGrid Code or View Layer Implementation
Or Detail Page which user can make Insert/update or delete process.
#model MvcMobile.ViewModel.SeminarListDetailViewModel
#{
ViewBag.Title = "Detail";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Detail</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Seminar</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Seminar.Seminar_Code)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Seminar.Seminar_Code)
#Html.ValidationMessageFor(model => model.Seminar.Seminar_Code)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Seminar.Title)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Seminar.Title)
#Html.ValidationMessageFor(model => model.Seminar.Title)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Seminar.Description)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Seminar.Description)
#Html.ValidationMessageFor(model => model.Seminar.Description)
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Seminar.Room)
</div>
</td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.Seminar.Room)
#Html.ValidationMessageFor(model => model.Seminar.Room)
</div>
</td>
</tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
<script type="text/javascript">
jQuery(document).ready(function () {
var AllSpeakers = (function () {
var list = null;
$.ajax({
'async': false,
'global': false,
'url': 'GetAllSpeakers',
'dataType': 'json',
'success': function (data) {
list = data;
}
});
return list;
})();
var AllTags = (function () {
var list = null;
$.ajax({
'async': false,
'global': false,
'url': 'GetAllTags',
'dataType': 'json',
'success': function (data) {
list = data;
}
});
return list;
})();
var lastSel = 0;
jQuery("#list").jqGrid({
url: '/Seminar/DetailGridData/',
editurl: "/Seminar/MyEdit/",
datatype: 'json',
mtype: 'GET',
colNames: ['Seminar_Code', 'Speaker', 'Tag', 'DateAndTime'],
colModel: [
{ name: 'Seminar_Code', index: 'Seminar_Code', width: 40, align: 'left', editable: true, edittype: "text", editoptions: { size: "35", maxlength: "50"} },
{ name: 'SpeakerID', index: 'SpeakerID', align: 'left', editable: true, edittype: "select", formatter: 'select', editoptions: { value: AllSpeakers,
dataEvents: [
{ type: 'change',
fn: function (e) {
//alert("Speaker change"); // For Cascading Dropdownlist Or Dependent Combo
}
}
]
}, editrules: { required: true}
},
{ name: 'TagID', index: 'TagID', align: 'left', editable: true, edittype: 'select', formatter: 'select', editoptions: { value: AllTags }, editrules: { required: true} },
{ name: 'DateAndTime', index: 'DateAndTime', width: 40, align: 'left', editable: true, edittype: "text", editoptions: { size: "35", maxlength: "50"} }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'SpeakerName',
sortorder: "desc",
viewrecords: true,
autowidth: true,
autoheight: true,
imgpath: '/scripts/themes/black-tie/images',
caption: 'My first grid'
})
$("#list").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false, refresh: false, search: false });
$("#list").jqGrid('inlineNav', '#pager', {
addtext: "Add",
edittext: "Edit",
savetext: "Save",
canceltext: "Cancel",
addParams: {
addRowParams: {
// the parameters of editRow used to edit new row
keys: true,
oneditfunc: function (rowid) {
alert("new row with rowid=" + rowid + " are added.");
}
}
},
editParams: {
// the parameters of editRow
key: true,
oneditfunc: function (rowid) {
alert("row with rowid=" + rowid + " is editing.");
}
},
cancelParams: {
key: true,
oneditfunc: function (rowid) {
//alert("row with rowid=" + rowid + " cancel.");
}
}
});
});
</script>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Controller Layer Code
public class SeminarController : Controller
{
ISeminarListDetailRepository seminarRepository;
//
// Dependency Injection enabled constructors
public SeminarController()
: this(new SeminarListDetailRepository()) {
}
public SeminarController(ISeminarListDetailRepository repository)
{
seminarRepository = repository;
}
/// <summary>
/// Just for Listing page.
/// </summary>
/// <returns></returns>
public ActionResult Index()
{
return View();
}
/// <summary>
/// Master Detail CRUD form according to previous form's choosen code.
/// </summary>
/// <param name="Seminar_Code"></param>
/// <returns></returns>
public ActionResult DetailByCode(string Seminar_Code)
{
return View();
}
/// <summary>
/// Master Detail CRUD form.
/// </summary>
/// <returns></returns>
public ActionResult Detail()
{
var SeminarListDetailViewModel = new SeminarListDetailViewModel();
return View(SeminarListDetailViewModel);
}
/// <summary>
/// It is this method what I really focus when it comes to save all rows of jqgrid at once.
/// </summary>
/// <param name="Seminar"></param>
/// <param name="Seminar_Details"></param>
/// <returns></returns>
[HttpPost]
public ActionResult Detail(Seminar Seminar, List<Seminar_Detail> Seminar_Details)
{
return View();
}
/// <summary>
/// Just for test purpose only.
/// I will not use this method when I know how to save JQGrid's All Rows at once.
/// </summary>
/// <param name="Seminar_Detail"></param>
/// <returns></returns>
public ActionResult MyEdit(Seminar_Detail Seminar_Detail)
{
//var seminar_Code = Seminar_Detail.Seminar_Code;
var jsonData = new
{
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public ActionResult GetAllSpeakers()
{
string AllSpeakers = " : ;";
var Speakers = seminarRepository.GetAllSpeakerList().Seminar_Item_Speaker;
for (int i = 0; i < Speakers.Count; i++)
{
if (i == Speakers.Count - 1)
{
///For the last row
AllSpeakers += Speakers[i].SpeakerID + ":" + Speakers[i].SpeakerName;
}
else
{
AllSpeakers += Speakers[i].SpeakerID + ":" + Speakers[i].SpeakerName + ";";
}
}
return Json(AllSpeakers, JsonRequestBehavior.AllowGet);
}
public JsonResult GetAllTags()
{
string AllTags = " : ;";
var Tags = seminarRepository.GetAllTagList().Seminar_Item_Tag;
for (int i = 0; i < Tags.Count; i++)
{
if (i == Tags.Count - 1)
{
///For the last row
AllTags += Tags[i].TagID + ":" + Tags[i].TagName;
}
else
{
AllTags += Tags[i].TagID + ":" + Tags[i].TagName + ";";
}
}
return Json(AllTags, JsonRequestBehavior.AllowGet);
}
public ActionResult DetailGridData(string sidx, string sord, int page, int rows)
{
int currentPage = Convert.ToInt32(page) - 1;
int totalRecords = 0;
var SeminarList = seminarRepository.GetSeminarDetail("CMP04").Seminar_Detail; //OrderBy(x => x.Seminar_Code).Skip(page * rows).Take(rows).ToList();
var totalPages = (int)Math.Ceiling(totalRecords / (float)rows);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from s in SeminarList
select new
{
id = s.Seminar_Code + "__" + s.SpeakerID + "__" + s.TagID,
cell = new object[]
{
s.Seminar_Code,
s.SpeakerID,
s.TagID,
s.DateAndTime
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public ActionResult ListingGridData(string sidx, string sord, int page, int rows)
{
int currentPage = Convert.ToInt32(page) - 1;
int totalRecords = 0;
var SeminarList = seminarRepository.AllSeminarList().Seminar_Masters; //OrderBy(x => x.Seminar_Code).Skip(page * rows).Take(rows).ToList();
var totalPages = (int)Math.Ceiling(totalRecords / (float)rows);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from s in SeminarList
select new
{
id = s.Seminar_Code,
cell = new object[]
{
s.Seminar_Code,
s.Title,
s.Description,
s.Room
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
Updated 2
Please let me make my question more clear.
I have two tables to insert data at once.
1.SeminarMaster(Seminar_Code, Title, Description, Room)
[At Razor View] - Form Input Fields
2.SeminarDetail(Seminar_Code, SpeakerID, TagID, DateAndTime)
[At Razor View] - JQGrid Rows and Columns
These two tables are in one-to-many relationship.
Update 3
I am really sorry for making my question unclear again and again.
Now please read my update again.I tried my best to make you clear understand my question.
Index.cshtml Or First time display form which user can select any row and go to detail page to make update.But Actually, below razor is not complete yet. Because I need to add Edit buttons at every rows of jqgrid. That Edit button will redirect to another page that I called Detail.cshtml by parsing selected Code. I will update it later. It is not my main problem.
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Seminar List</h2>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
#Html.ActionLink("Click here", "Detail") to add new data.
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Seminar/ListingGridData/',
editurl: "/Seminar/MyEdit/",
datatype: 'json',
mtype: 'GET',
colNames: ['Seminar_Code', 'Title', 'Description', 'Room'],
colModel: [
{ name: 'Seminar_Code', index: 'Seminar_Code', width: 40, align: 'left', editable: false },
{ name: 'Title', index: 'Title', width: 40, align: 'left', editable: false },
{ name: 'Description', index: 'Description', width: 40, align: 'left', editable: false },
{ name: 'Room', index: 'Room', width: 40, align: 'left', editable: false }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Title',
sortorder: "asc",
viewrecords: true,
autowidth: true,
autoheight: true,
caption: 'Seminar List - Grid'
})
});
</script>
Every suggestion will be appreciated.

Categories