Multiple columns in popup edit mode - asp.net-mvc

I think the popup edit mode is the nicest of the edit modes, but with a larger model the popup becomes very long which doesn't look nice.
I've found a solution for this and I'm curious on your ideas/feedback/enhancements for this solution.
I created two custom attributes:
public class NumberOfColumnsAttribute : Attribute, IMetadataAware
{
private readonly int _numberOfColumns;
public NumberOfColumnsAttribute(int numberOfColumns)
{
_numberOfColumns = numberOfColumns;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
if (!metadata.AdditionalValues.ContainsKey("NumberOfColumns"))
{
metadata.AdditionalValues.Add("NumberOfColumns", _numberOfColumns);
}
}
}
public class ShowInColumnAttribute : Attribute, IMetadataAware
{
private readonly int _column;
public ShowInColumnAttribute(int column)
{
_column = column;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
if (!metadata.AdditionalValues.ContainsKey("ShowInColumn"))
{
metadata.AdditionalValues.Add("ShowInColumn", _column);
}
}
}
Then use the [NumberOfColumns(m)] attribute above your edit model and use the [ShowInColumn(n)] attribute above a property (n=1 is assumed when no attribute is applied).
I created a Object.cshtml file in Views/Shared/EditorModels/ as follows.
#if (ViewData.TemplateInfo.TemplateDepth > 1)
{
#ViewData.ModelMetadata.SimpleDisplayText
} else {
for (var i = 1; i <= (int)(!ViewData.ModelMetadata.AdditionalValues.ContainsKey("NumberOfColumns") ? 1 : ViewData.ModelMetadata.AdditionalValues["NumberOfColumns"]);i++)
{
<div class="editor-column">
#foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm) && ((int)(!pm.AdditionalValues.ContainsKey("ShowInColumn") ? 1 : pm.AdditionalValues["ShowInColumn"])) == i))
{
if (prop.HideSurroundingHtml) {
#Html.Editor(prop.PropertyName)
} else {
<div class="editor-label">
#Html.Label(prop.PropertyName)
#(prop.IsRequired ? "*" : "")
</div>
<div class="editor-field">
#Html.Editor(prop.PropertyName)
#Html.ValidationMessage(prop.PropertyName, "*")
</div>
}
}
</div>
}
<div class="editor-seperator"></div>
}
And the following lines of CSS:
.k-edit-form-container {
width: auto;
}
.editor-column {
width: 400px;
float: left;
}
.editor-seperator {
clear: both;
}
What do you think?

I think, this would be much simpler. Please run this script on wide screen.
var crudServiceBaseUrl = "//demos.telerik.com/kendo-ui/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true } },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
toolbar: ["create"],
columns: [
{ field:"ProductName", title: "Product Name" },
{ field: "UnitPrice", title:"Unit Price", format: "{0:c}", width: "120px" },
{ field: "UnitsInStock", title:"Units In Stock", width: "120px" },
{ field: "Discontinued", width: "120px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }],
editable: "popup",
edit: fnMultipleLayoutForm
});
function fnMultipleLayoutForm(){
$(".k-edit-form-container").prepend('<div class="column1" style="display: inline-block; float: left;padding-right:30px"></div><div class="column2" style="display: inline-block;float: left;padding-right:30px;"></div>');
$(".k-edit-form-container").children(".k-edit-label, .k-edit-field").slice(0, parseInt($(".k-edit-form-container").children(".k-edit-label, .k-edit-field").length / 2)).appendTo(".column1");
$(".k-edit-form-container").children(".k-edit-label, .k-edit-field").appendTo(".column2");
$(".k-edit-form-container").css("width", "auto");
$('.k-window').css({ top: '50%', left: '50%', margin: '-' + ($('.k-window').height() / 2) + 'px 0 0 -' + ($('.k-window').width() / 2) + 'px' });
};
<script src="//kendo.cdn.telerik.com/2015.3.1111/js/jquery.min.js"></script>
<script src="//kendo.cdn.telerik.com/2015.3.1111/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2015.3.1111/styles/kendo.common.min.css" />
<link rel="stylesheet" href="//kendo.cdn.telerik.com/2015.3.1111/styles/kendo.default.min.css" />
<div id="grid"></div>

Related

Leaflet use popup not display

I use highchart chart to present in popup.
It can be presented when the marker is clicked for the first time.
But opening another popup cannot display the chart.
If I close the original one and open a new one, it can be displayed.
What is the problem?
Turn on for the first time
When opening another
Code:
function onEachFeature(feature, layer) {
var popupContent = '<p style="font-size:130%;">' + feature.properties.id + "<br>PM2.5: " + air + '</p><div class="d-flex"> <button class="day-button">24 hr</button> <button class="week-button">7 Days</button> <button class="mon-button ">30 Days</button></div>' + '</p><div id="container" style="min-width: 350px; height: 190px; margin: 0 auto"></div> <p> ';
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent, { minWidth: 370 }).on("popupopen", function(e) {
var id1 = feature.properties.id;
Highcharts.setOptions({ global: { useUTC: false } });
var chart = null;
test(id1);
}
}
Highchart:
function test (station){
var ob = [];
var json_hour ="data.csv";
var count_nul = 0;
d3.csv(json_hour, function (error, result) {
function date_to_epoch(key) {
var epoch_seconds = new Date(key).getTime();
return Math.floor(epoch_seconds);
}
for (var i = 0; i < result.length; i++) {
var apoche = date_to_epoch(result[i]['date']).toString();
apoche = parseFloat(apoche);
if (parseFloat(result[i]['pm25']).toString() == 'NaN') {
count_nul++;
} else {
var miles = parseFloat(result[i]['pm25']);
}
ob.push([apoche, miles]);
}
if (count_nul >= 24) {
$("#con").text("no data");
}
else {
$("#con").empty();
console.log((ob));
new Highcharts.Chart({
chart: {
renderTo: 'con',
type: 'line'
},
title: { text: '' },
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
minute: '%H:%M',
hour: '%H:%M',
day: '%Y<br/>%m%d',
week: '%Y<br/>%m-%d',
month: '%Y<br/>%m',
year: '%Y'
}
, crosshair: true,
},
tooltip: {
split: false,
shared: true,
animation: true,
xDateFormat: '%Y-%m-%d %H:%M',
valueSuffix: ' µm'
},
series: [{
name: "PM2.5",
data: ob,
showInLegend: true
}
],
credits: {
enabled: false
},
exporting: {
enabled: false
},
plotOptions: {
line: {
connectNulls: true,
}
},
responsive: {
rules: [{
condition: {
maxWidth: 330
},
}]
}
});
}
});
}
Change your code to:
function onEachFeature(feature, layer) {
var popupContent = '<p style="font-size:130%;">' + feature.properties.id + "<br>PM2.5: " + air + '</p><div class="d-flex"> <button class="day-button">24 hr</button> <button class="week-button">7 Days</button> <button class="mon-button ">30 Days</button></div>' + '</p><div id="container" style="min-width: 350px; height: 190px; margin: 0 auto"></div> <p> ';
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent, { minWidth: 370 }).on("popupopen", function(e) {
var id1 = e.popup._source.feature.properties.id;
Highcharts.setOptions({ global: { useUTC: false } });
var chart = null;
test(id1);
}
}
With e.popup._source.feature.properties.id you are sure that the id is from the current open layer

I have list of users which is used to send mail to them. I want to display selected users in another list box. How can I do that?

I have following code which displays list of users and when i select user and click on send, it sends mail. But I want to display another list which takes users from selected values and then send mail.
View Code:
<div class="modal fade small" id="invitiesModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h5 class="modal-title" id="myModalLabel">Share</h5>
</div>
<div class="modal-body">
<table id="tblMeeting"> </table>
<div id="pager"></div>
</div>
<input type="hidden" value="0" id='meetingId' name='meetingId'>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnShareMOM" data-dismiss="modal">Send Mail</button>
</div>
</div>
</div>
</div>
JQGrid:
var idsOfSelectedRows = new Array();
$("#DraftFile").change(function () {
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById("mom_btn1").style.display = "inline-block";
document.getElementById("mom_btn2").style.display = "inline-block";
}
});
checkName = function (value) {
//debugger;
if (value.length == 0) {
return [false, "Please enter the Name!"]
}
return [true];
};
function ShareMOM(meetingId) {
var InvityIds = new Array();
//alert(meetingId);
$.ajax({
url: '#Url.Action("ShareView", "PostMeetingDocument", new { area = "Postmeeting" })',
type: "Get",
async: false,
data: { "meetingId": meetingId },
cache: false,
success: function (data) {
InvityIds = data;
//console.log(data);
},
error: function () {
//alert('oops something wrong!!');
}
})
idsOfSelectedRows = new Array();
//$.each(InvityIds, function (index, val) {
// idsOfSelectedRows.push(val);
//});
var updateIdsOfSelectedRows = function (id, isSelected) {
var contains = idsOfSelectedRows.indexOf(id);
if (!isSelected && contains>=0) {
for (var i = 0; i < idsOfSelectedRows.length; i++) {
if (idsOfSelectedRows[i] == id) {
idsOfSelectedRows.splice(i, 1);
break;
}
}
}
else if (contains<0) {
idsOfSelectedRows.push(id);
}
};
$("#tblMeeting").jqGrid("GridUnload")
$("#meetingId").val(meetingId);
$("#Invities").show();
var URL = '#Url.Action("GetInvitees", "PostMeetingDocument", new { area = "Postmeeting", meetingId = "_MeetingId" })';
URL = URL.replace("_MeetingId", meetingId);
$('#tblMeeting').jqGrid({
url: URL,
datatype: "json",
mytype: "GET",
colNames: ["UserID", "FirstName","LastName"],
colModel: [
{ name: 'UserID', index: 'UserID', width: 55, hidden: true, key: true, editable: false, checked: true },
{ name: 'FirstName', index: 'FirstName', sortable: false, align: "left", width: 150, editable: true, search: false, editrules: { custom: true, custom_func: checkName }, searchoptions: { sopt: ['cn'] } },
{ name: 'LastName', index: 'LastName', sortable: false, align: "left", width: 150, editable: true, search: false, editrules: { custom: true, custom_func: checkName } },
//{ name: 'Department', index: 'Department', sortable: false, align: "left", width: 150, editable: true, search: false, editrules: { custom: true, custom_func: checkName } }
],
rowNum: 30,
rowList: [30, 60, 90],
multiSort: true,
sortname: 'FirstName asc,LastName',
sortorder: 'asc',
height: 350,
pager: jQuery('#pager'),
width: 510,// 450,
multiselect: true,
multiPageSelection: true,
viewrecords: true,
//caption: "Add Invities",
onSelectRow: function (rowid, status) {
//selected[rowid] = status;
//setSelectedDeviceCount();
updateIdsOfSelectedRows(rowid, status);
},
onSelectAll: function (aRowids, status) {
var i, count, id;
for (i = 0, count = aRowids.length; i < count; i++) {
//selected[rowids[i]] = status;
id = aRowids[i];
updateIdsOfSelectedRows(id, status);
}
},
loadComplete: function () {
$.each(idsOfSelectedRows, function (index, val) {
//var ids = grid.jqGrid('getDataIDs');
//for (var i = 0; i < ids.length; i++) {
// if (selected[ids[i]] === true) {
// grid.setSelection(ids[i], false);
// }
//}
$('#tblMeeting').jqGrid("setSelection", val, true);
});
},
shrinkToFit: true
}).navGrid(pager, { edit: false, add: false, del: false, search: false, refresh: true, addtext: "Share MOM", searchtext: "Search", refreshtext: "Refresh" },
{
//Edit.
},
{
// add options.
},
{
//Delete.
}
);
}
$("#btnShareMOM").on('click', function () {
//var UserId = new Array();
$.ajax({
url: '#Url.Action("SendMomAll", "PostMeetingDocument", new { area = "Postmeeting" })',
type: "Get",
async: false,
data: { "meetingId": $("#MeetingID").val(), "userId": idsOfSelectedRows.join() },
cache: false,
success: function (data) {
// InvityIds = data;
//console.log(data);
},
error: function () {
//alert('oops something wrong!!');
}
})
});
Controller:
public ActionResult SendMomAll(int meetingId, string userId)
{
var EmailTemplate = db.EmailTempletes.Where(l => l.Name == "FinalMOM").FirstOrDefault();
List<int> userIds = Array.ConvertAll<string, int>(userId.Split(','), new Converter<string, int>(Convert.ToInt32)).ToList();
List<string> UserMailList = (from u in db.VMUsers where userIds.Contains(u.UserID) select u.Email.Trim()).ToList();
string UserMail = string.Join(",", UserMailList.ToArray());
//var Note = db.Notes.OrderByDescending(l => l.NoteId).FirstOrDefault(l => (l.PreviousNoteId == (-1) || l.PreviousNoteId == (-2)) && (l.ParentNoteId == (-1) || l.ParentNoteId == (-2)) && l.MeetingId == meetingId);
//var Note = db.Notes.OrderByDescending(l => l.NoteId).FirstOrDefault(l => l.MeetingId == meetingId);
//var Document = db.Files.OrderByDescending(l => l.FileId).FirstOrDefault(l => l.NoteId == Note.NoteId);
var strMappath = Server.MapPath("~/Repository/Meetings/" + meetingId.ToString() + "/");
//strMappath += Document.FileName;
var dir = new DirectoryInfo(strMappath).GetFiles("*.*").OrderByDescending(l=>l.LastWriteTime).FirstOrDefault();
MailBox mailbox = new MailBox();
mailbox.MailTo = UserMail;
mailbox.Subject = EmailTemplate.Subject;
mailbox.Body = EmailTemplate.TempleteBody;
mailbox.IsAttachment = true;
mailbox.AttachmentsPath = strMappath + dir.Name;
mailbox.Status = false;
db.MailBox.Add(mailbox);
db.SaveChanges();
//return View("Index");
return Json(mailbox,JsonRequestBehavior.AllowGet);
}
Now i want to display list for selected users from this list

JS grid not showing in Partial View MVC

In my project am showing js grid from partial view. so tried like this
View
<div id="searchgrid" class="col-lg-12">
#Html.Partial("ResultGrid", new List<SCM_MVC.Models.User>(), new ViewDataDictionary(this.ViewData) { { "index" , ViewData["Form"] } })
</div>
<script src="~/assets/js/jquery-1.10.2.js"></script>
<script>
var url = '#Url.Action("ResultGrid", "User", new { xEdit = ViewData["Form"]})';
$('#btnloadgrid').click(function () {
$('#searchgrid').load(url);
})
</script>
Partial View
#model IEnumerable<SCM_MVC.Models.User>
#{
/**/
/**/
#section head {
#*<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/demos.css" />*#
<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/jsgrid.css" />
<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/theme.css" />
<script src="~/SCM/jsgrid/js/jquery-1.8.3.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.core.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.load-indicator.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.load-strategies.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.sort-strategies.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.field.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.core.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.text.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.number.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.select.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.checkbox.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.control.js"></script>
}
/**/
<table id="jsGrid"></table>
#section scripts {
<script src="http://js-grid.com/js/jsgrid.min.js"></script>
<script>
$(function () {
$("#jsGrid").jsGrid({
height: "70%",
width: "100%",
filtering: true,
editing: true,
inserting: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete the user?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "/api/data",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "/api/data",
data: item,
dataType: "json"
});
},
updateItem: function (item) {
return $.ajax({
type: "PUT",
url: "/api/data/" + item.ID,
data: item,
dataType: "json"
});
},
deleteItem: function (item) {
return $.ajax({
type: "DELETE",
url: "/api/data/" + item.ID,
dataType: "json"
});
}
},
fields: [
{ name: "user_id", title: Resources.Resource.user_id, type: "text", width: 150 },
{ name: "username", title: Resources.Resource.user_name, type: "text", width: 50 },
{ name: "mailid", title: Resources.Resource.mailid, type: "text", width: 200 },
{ name: "role", title: Resources.Resource.role, type: "text", width: 50 },
{ name: "dept", title: Resources.Resource.dept, type: "text", width: 100 },
{ name: "designation", title: Resources.Resource.designation, type: "text", width: 100 },
{ name: "city", title: Resources.Resource.city, type: "text", width: 100 },
{ name: "country", title: Resources.Resource.country, type: "text", width: 100 },
{ type: "control" }
]
});
});
</script>
}
}
DataController
namespace SCM_MVC.Controllers
{
public class DataController : ApiController
{
// GET: Data
public IEnumerable<object> Get()
{
//ClientFilter filter = GetFilter();
//var result = DB.Client.Where(c =>
// (String.IsNullOrEmpty(filter.Name) || c.Name.Contains(filter.Name)) &&
// (String.IsNullOrEmpty(filter.Address) || c.Address.Contains(filter.Address)) &&
// (!filter.Married.HasValue || c.Married == filter.Married) &&
// (!filter.Country.HasValue || c.Country == filter.Country)
//);
Models.User xuser = new Models.User();
List<Models.User> xuserlist = new List<Models.User>();
//if (ViewData["index"] == null)
//{
// ViewData["index"] = xEdit;
//}
xuser.UserId = "US-0001";
xuser.UserName = "Robert";
xuser.Mailid = "robert#gmail.com";
xuser.Role = "Admin";
xuser.Designation = "Sales Admin";
xuser.Dept = "Sales";
xuser.State = "Tamil Nadu";
xuser.Country = "India";
xuserlist.Add(xuser);
return xuserlist;
}
}
}
UserController
public ActionResult ResultGrid(string xEdit)
{
Models.User xuser = new Models.User();
List<Models.User> xuserlist = new List<Models.User>();
xuser.UserId = "US-0001";
xuser.UserName = "Robert";
xuser.Mailid = "robert#gmail.com";
xuser.Role = "Admin";
xuser.Designation = "Sales Admin";
xuser.Dept = "Sales";
xuser.State = "Tamil Nadu";
xuser.Country = "India";
xuserlist.Add(xuser);
return PartialView(xuserlist);
}
But in Screen its not showing. What am doing wrong here?
Thanks
Am using Visual Studio 2017 ASP.Net MVC

How to filter array type of resource in Telerik MVC Scheduler?

I'm trying to filter calendar MeetingAttendees which can have multiple users. I've built a filter and tested with various options, but it doesn't work. The basic example shows how to filter a calendar owner (which is a single value) and it works fine for me. But Attendees is an array and when I'm trying to filter that all my events disappear.
Here is my filter code:
var checked = $.map($("#teamMembers :checked"), function (checkbox) {
return parseInt($(checkbox).val());
});
var filter = {
logic: "or",
filters: $.map(checked, function (value) {
return {
operator: "eq",
field: "Attendees",
value: value
};
})
};
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler.dataSource.filter(filter);
Attendees in MeetingViewModel are loaded as an array:
Attendees = meeting.MeetingAttendees.Select(m => m.AttendeeID).ToArray(),
Here is the scheduler configuration:
#(Html.Kendo().Scheduler<Itsws.Models.MeetingViewModel>()
.Name("scheduler")
.Date(DateTime.Today)
.Editable(editable =>
{
editable.TemplateName("CustomEditorTemplate");
})
.StartTime(new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 7, 00, 00))
.Height(600)
.Views(views =>
{
views.DayView();
views.WeekView(weekView => weekView.Selected(true));
views.MonthView();
views.AgendaView();
views.TimelineView();
})
.Timezone("Etc/UTC")
.DataSource(d => d
.Model(m =>
{
m.Id(f => f.MeetingID);
m.Field(f => f.Title).DefaultValue("No title");
m.RecurrenceId(f => f.RecurrenceID);
m.Field(f => f.Title).DefaultValue("No title");
})
.Read("Meetings_Read", "Scheduler")
.Create("Meetings_Create", "Scheduler")
.Destroy("Meetings_Destroy", "Scheduler")
.Update("Meetings_Update", "Scheduler")
)
)
Apparently operator field can also be a function that does filter comparison. Here is the sample code generously provided by Telerik support.
More info here:
http://www.telerik.com/forums/how-to-filter-array-type-of-resource-(e-g-attendees)
<!DOCTYPE html>
<html>
<head>
<base href="http://demos.telerik.com/kendo-ui/scheduler/resources-grouping-vertical">
<style>html { font-size: 12px; font-family: Arial, Helvetica, sans-serif; }</style>
<title></title>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.moonlight.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.dataviz.moonlight.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.408/styles/kendo.default.mobile.min.css" />
<script src="http://cdn.kendostatic.com/2015.1.408/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.408/js/kendo.all.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.408/js/kendo.timezones.min.js"></script>
</head>
<body>
<div id="example" class="k-content">
<div id="team-schedule">
<div id="attendees">
<ul>
<li>Alex: <input type="checkbox" id="alex" value="1"></li>
<li>BoB: <input type="checkbox" id="bob" value="2"></li>
<li>Charlie: <input type="checkbox" id="charlie" value="3"></li>
</ul>
</div>
</div>
<div id="scheduler"></div>
</div>
<script>
$(function() {
$("#scheduler").kendoScheduler({
date: new Date("2013/6/13"),
height: 600,
views: [
"timelineMonth"
],
timezone: "Etc/UTC",
dataSource: {
batch: true,
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/meetings",
dataType: "jsonp"
},
update: {
url: "http://demos.telerik.com/kendo-ui/service/meetings/update",
dataType: "jsonp"
},
create: {
url: "http://demos.telerik.com/kendo-ui/service/meetings/create",
dataType: "jsonp"
},
destroy: {
url: "http://demos.telerik.com/kendo-ui/service/meetings/destroy",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
schema: {
model: {
id: "meetingID",
fields: {
meetingID: { from: "MeetingID", type: "number" },
title: { from: "Title", defaultValue: "No title", validation: { required: true } },
start: { type: "date", from: "Start" },
end: { type: "date", from: "End" },
startTimezone: { from: "StartTimezone" },
endTimezone: { from: "EndTimezone" },
description: { from: "Description" },
recurrenceId: { from: "RecurrenceID" },
recurrenceRule: { from: "RecurrenceRule" },
recurrenceException: { from: "RecurrenceException" },
roomId: { from: "RoomID", nullable: true },
attendees: { from: "Attendees", nullable: true },
isAllDay: { type: "boolean", from: "IsAllDay" }
}
}
}
},
group: {
resources: ["Rooms", "Attendees"],
orientation: "vertical"
},
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: [
{ text: "Meeting Room 101", value: 1, color: "#6eb3fa" },
{ text: "Meeting Room 201", value: 2, color: "#f58a8a" }
],
title: "Room"
},
{
field: "attendees",
name: "Attendees",
dataSource: [
{ text: "Alex", value: 1, color: "#f8a398" },
{ text: "Bob", value: 2, color: "#51a0ed" },
{ text: "Charlie", value: 3, color: "#56ca85" }
],
multiple: true,
title: "Attendees"
}
]
});
$("#attendees :checkbox").change(function(e) {
var checked = $.map($("#attendees :checked"), function(checkbox) {
return parseInt($(checkbox).val());
});
var scheduler = $("#scheduler").data("kendoScheduler");
scheduler.dataSource.filter({
field: "attendees",
operator: function(item, value) {
var found = true;
for (var i = 0; i < checked.length; i++) {
if (item.indexOf(checked[i]) < 0) {
found = false;
}
}
return found;
}
});
});
});
</script>
</body>
</html>

Post Data to the action result when Dropdown list change in ASP.NET MVC using jqgrid

I have Created JqGrid for loading some records like below.
<script type="text/javascript">
$(document).ready(function () {
$('#jqgRequests').jqGrid({
defaults: {
recordtext: "View {0} - {1} of {2}",
emptyrecords: "No Request Found",
loadtext: "Loading...",
pgtext: "Page {0} of {1}"
},
//url from wich data should be requested
url: '#Url.Action("LoadRequest")',
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: ['Is Approved','Requestor', 'Request Type', 'Request Date', 'Approved Date', 'Package','Comments','RequestID', '','',''],
//columns model
colModel: [
{ name: 'IsApproved',
formatter: function (cellvalue, options, rowObject) {
var status = rowObject[0];
if (status == 1) {
return '<input type="checkbox" name="approval" checked disabled="disabled">';
}
else if(status==2) {
return '<img src="#Url.Content("~/Content/images/reject.jpg")"></img>';
}
else{
return '<input type="checkbox" name="approval" disabled="disabled" >';
}
},sortable:false, align: 'center', width: 80, index: 'subColumn'
},
{ name: 'Requestor', index: 'Requestor', width: 170, align: 'left' },
{ name: 'Request Type', index: 'RequestType', width: 90, align: 'left' },
{ name: 'RequestDate', index: 'RequestDate', formatter: 'date', formatoptions: { srcformat: 'FullDateTime', newformat: 'd/m/Y g:i:s A' }, width: 120, align: 'left' },
{ name: 'ApprovedDate', index: 'ApprovedDate', formatter: 'date', formatoptions: { srcformat: 'FullDateTime', newformat: 'd/m/Y g:i:s A' }, width: 120, align: 'left' },
{ name: 'Package', index: 'Package', width: 150, align: 'left' },
{ name: 'Comments', index: 'Comments', width: 300, align: 'left' },
{ name: 'RequestID', index: 'RequestID', width: 1, align: 'left',hidden:true },
{ name: 'Approve',
formatter: function (cellvalue, options, rowObject) {
var status = rowObject[0];
if(status==1)
{
return '#Html.ActionLink("Approve", null, null, new { #style = "color:blue;font-weight:bold;", onclick = "return WarningPopup('Already approved');", href = "#" })';
}
else{
var x = '#Html.ActionLink("Approve", null, null, new { #style = "color:Blue;font-weight:bold;", onclick = "return ConfirmPopup('myId');", href = "#" })';
// var x = '#Html.ActionLink("Approve", "Approve", "Dashboard", new { requestId = "myId" }, new { #style = "color:Blue;font-weight:bold;", onclick = "return confirm('Are you sure to approve this request?');" })';
return x.replace("myId",rowObject[7]);
}
},sortable:false, align: 'left', width: 45
},
{ name: 'Reject',
formatter: function (cellvalue, options, rowObject) {
var status = rowObject[0];
if(status==2)
{
return '#Html.ActionLink("Reject", null, null, new { #style = "color:blue;font-weight:bold;", onclick = "return WarningPopup('Already rejected');", href = "#" })';
}
else{
var x = '#Html.ActionLink("Reject", null, null, new { #style = "color:Blue;font-weight:bold;", onclick = "return Rejectpopup('myId');", href = "#" })';
// var x = '#Html.ActionLink("Reject", "Reject", "Dashboard", new { requestId = "myId" }, new { #style = "color:Blue;font-weight:bold;", onclick = "return confirm('Are you sure to reject this request?');" })';
return x.replace("myId",rowObject[7]);
}
},sortable:false, align: 'left', width: 60
},
{ name: 'More',
formatter: function (cellvalue, options, rowObject) {
// var x = "<a class='btnMore' onclick='GetDetail('myId');' style = 'color:blue;font-weight:bold;' href='#'>More Detail</a>"
var x='#Html.ActionLink("Detail", null, null, new { #style = "color:blue;font-weight:bold;", onclick = "return GetDetail('myId');", href = "#" })';
return x.replace("myId",rowObject[7]);
},sortable:false, align: 'left', width: 80
}
],
//pager for grid
pager: $('#jqgpRequests'),
//number of rows per page
rowNum: 25,
//initial sorting column
sortname: 'RequestID',
//initial sorting direction
sortorder: 'asc',
//we want to display total records count
viewrecords: true,
//grid height
height: '100%'
});
});
</script>
Action Result
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult LoadRequest(JqGridRequest request)
{
int totalRecords = _dashboardRepository.RequestCount;
var response = new JqGridResponse()
{
TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
PageIndex = request.PageIndex,
TotalRecordsCount = totalRecords
};
const string subColumn = "";
foreach (var dashboard in _dashboardRepository.LoadAllRequests(request.SortingName, request.SortingOrder.ToString(), request.PageIndex, request.RecordsCount))
{
response.Records.Add(new JqGridRecord(dashboard.RequestID.ToString(), new List<object>()
{
dashboard.IsApproved,
dashboard.Requestor,
dashboard.RequestType,
dashboard.RequestDate,
dashboard.ApprovedDate,
dashboard.Package,
dashboard.Comments,
dashboard.RequestID
}));
}
return new JqGridJsonResult { Data = response };
}
This jqGrid load when the page load. Also i have added a dropdown list for filtering. For this i need to post some parameters for the JqGridRequest class . How can i possible this?
Assuming that your dropdown id is ddlFilter you can write the JavaScript change event handler like this:
$('#ddlFilter').on('change', function(e) {
$('#jqgRequests').setGridParam({ postData: { FilterValue: $(this).val(); } }).trigger('reloadGrid', [{ page: 1 }]);
});
On server side you can create following view model for handling the post data:
public class PostDataViewModel
{
public string FilterValue { get; set; }
}
And add it as one more parameter to your action:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult LoadRequest(JqGridRequest request, PostDataViewModel postData)
{
...
}
Unless there is some specifc requirement or edge case you haven't describe in your question this should do the trick.
If I understand you correct you can follow the suggestion from the old answer.
If you have for example <select id="mySelect">...</select> on the page you can use jqGrid option
postData: {
myFilter: function () {
return $("#mySelect option:selected").val();
}
}
to send the value of the select box together with other standard jqGrid parameters (see JqGridRequest). If you want additionally to reload the grid after every changes of the select you can use .trigger("reloadGrid"). You need just set change and keyup event handler and calls .trigger("reloadGrid") it it require. See the answer for more code example.

Resources