Select2 Add New Tag if no result returned in search - ajax

I have dropdown list where , after typing 2 or more symbols it starts to search in base nad returns values . if none is searched i want user to be able to add that tag as new one. here is my code so far
$("#tags,#TagId").select2(
{
allowClear: true,
ajax: {
url: "/Entry/ReadSelect2DataMulti",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term,
page: params.page || 1
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data
};
},
cache: true,
error: function (xhr, textStarus, error) {
}
},
minimumInputLength: 2,
placeholder: "აირჩიეთ პოზიცია",
templateResult: function (state) {
var result = '<div class="pos-template">' + '<span title=""><b>' + state.text + '</b></span>';
if (state.content != null && state.content != '') {
var tags = state.content.split(",");
for (i = 0; i < tags.length; i++) {
result = result + '<span class="pos-tag">' + tags[i] + '</span>';
}
} else {
}
result = result + '</div></div>';
return $(result);
},
createSearchChoice: function (term, data) {
if ($(data).filter(function () {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return { id: term, text: term };
}
},
language: {
noResults: function () {
return "პოზიცია ვერ მოიძებნა";
},
inputTooShort: function () {
return "შეავსეთ მინიმიმ 2 სიმბოლო";
},
loadingMore: function () {
return 'იტვირთება...';
},
searching: function () {
return 'იფილტრება...';
}
}
}
);
But this createSearch doesnt do anything.
<div class="form-group">
<select multiple="multiple" class="form-control" id="tags" style="width: 400px;"></select>
</div>
this is my div part . any suggestions ?

Related

Prop mutating warning in VUE

I got an vue-warning (which results to as an error on my end coz my code is not working) that says:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "editmode"
With it, tried the suggestion here but can't make it work. Below is my work:
props:{
editmode:{
type: Boolean,
default: false,
}
},
methods:{
toggleM(){
var editmode = this.editmode;
editmode = !editmode;
this.editmode = editmode;
if(editmode == false){
//dothis
}else{
//dothat
}
},
}
TEMPLATE
<template>
<div class="ui-table-container-body">
<div class="ui-table" v-if="Boolean(items.length) || Boolean(Object.keys(items).length)" v-cloak>
<ui-table-body ref="body" v-model="items"
:editmode="editmode"
>
</ui-table-body>
</div>
</div>
</template>
The line this.editmode = editmode; is the one pointed in my console, is there any way I can surpass this?
You must use a data variable as a gateway to your prop.
In your component, the code code should look like this:
props:{
editmode:{
type: Boolean,
default: false,
}
},
data: {
dataEditMode = false
},
watch: {
'editmode': {
handler: 'onEditmodeChanged',
immediate: true,
},
'dataEditMode': {
handler: 'onDataEditModeChanged'
}
},
methods:{
toggleM(){
var editmode = this.dataEditMode;
editmode = !editmode;
this.dataEditMode = editmode;
if(editmode == false){
//dothis
}else{
//dothat
}
},
onEditmodeChanged (newVal) {
this.dataEditMode = newVal
},
onDataEditModeChanged (newVal) {
this.$emit('editmodeChanged', newVal)
}
}
and the the inclusion of this component in your parent-component should look like this:
<my-component-name :editmode="editmode" #editmodeChanged="(e) => { editmode = e }"></my-component-name>
You shouldn't mutate props from the component itself. See the One Way Data Flow section of the guide. You can use a prop as the initial value, and then keep a value in the data section and mutate that:
props: {
editmode: {
type: Boolean,
default: false,
}
},
data () {
return {
emode: this.editmode,
}
},
methods: {
toggleM () {
let editmode = this.emode;
editmode = !editmode;
this.emode = editmode;
if (editmode == false) {
// dothis
} else {
// dothat
}
},
}
Demo
Vue.component('editbox', {
template: '<div>' +
'<button #click="toggleM">{{ btext }}</button>' +
'<input v-if="emode" />' +
'</div>',
props: ['editmode'],
data () {
return {
emode: this.editmode,
}
},
computed: {
btext () {
return this.emode ? "Text" : "Edit";
}
},
methods:{
toggleM() {
this.emode = !this.emode;
},
}
})
var app = new Vue({
el: '#app',
data: {
mode: true,
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<editbox :editmode="mode" />
</div>
I would send back an event to the parent so it could modify its value:
For example (not tested):
Child Component
props:{
editmode:{
type: Boolean,
default: false,
}
},
methods:{
toggleM(){
var editmode = !this.editmode;
this.$emit('changeEditMode', editmode);
if (editmode == false){
//dothis
} else {
//dothat
}
},
}
Parent
<child-component #changeEditMode="editModeChanged" :editmode="editmode"></child-component>
...
methods:{
editModeChanged(value){
this.editmode = value
},
}

Hidden Field Excel Export In kendo ui

Requirement How to excel export hidden fields using kendoui grid
By using kendo editor i have implemented grid and i want to export hidden field using Excel export in kendo ui Grid Here I want to export Id field in Excel which is hidden here
My main moto is to export the hidden columns using excel export
<div id='grid-container'>
<div id='student-details-grid'
data-role='grid'
data-groupable='true'
data-sortable='true'
data-toolbar=['excel']
data-excel="{fileName: 'StudentDetails.xlsx', proxyURL: '/save', filterable: true, allPages: true}"
data-height='450px'
data-pageable="[
{'refresh':'true' },
{ 'pageSizes':'true'},
{'buttonCount':'5'}
]"
data-bind='source:gridDataSource'
data-columns="[{'field':'Id','title':'Id'},{'field':'Name','title':'Name'},{'field':'FatherName','title':'FatherName'},{'field':'Email','title':'Email'},{'field':'Address','title':'Address'},{'field':'ContactNo','title':'ContactNo'}]"
style="height: 550px">
</div>
</div>
<script type="text/javascript">
var viewModel = '';
$(document).ready(function (e) {
viewModel = kendo.observable({
gridDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Home/GetStudents",
dataType: "json"
}
},
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false, nullable: true },
Name: { validation: { required: true } },
FatherName: { type: "text", validation: { required: true, min: 1 } },
Email: { type: 'email', validation: { min: 0, required: true } },
Address: { type: "text", validation: { min: 0, required: true } },
ContactNo: { type: 'text', validation: { min: 0, required: true } },
}
},
parse: function (data) {
debugger
if (!data.success && typeof data.success !== 'undefined') {
gridDataSource.read();
}
if (data.success) {
viewModel.gridDataSource.read();
}
return data;
}
}
}),
});
kendo.bind($("#grid-container"), viewModel);
});
</script>
*Global variable
isExport = false;
data-bind="source: dataSource,events:{excelExport : onExcelExport}"
onExcelExport: function (e) {
var sheet = e.workbook.sheets[0];
for (var rowIndex = 1; rowIndex < sheet.rows.length; rowIndex++) {
var row = sheet.rows[rowIndex];
for (var cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
if (cellIndex === 6 || cellIndex === 8 || cellIndex === 20)
row.cells[cellIndex].format = "HH:mm"
}
}
var gridcolumn = e.sender.columns;
if (!isExport) {
$.each(gridcolumn, function (index, value) {
if (value.hidden)
e.sender.showColumn(index);
else if (value.hidden === false)
e.sender.hideColumn(index);
e.sender.hideColumn(0);
});
e.preventDefault();
isExport = true;
setTimeout(function () {
e.sender.saveAsExcel();
});
} else {
$.each(gridcolumn, function (index, value) {
if (value.hidden === false)
e.sender.hideColumn(index);
else
e.sender.showColumn(index);
});
isExport = false;
}
},

Jquery Selected Rows Value

I have a datatable. I want to retrieve the ID values of the rows that are selected.
How can I do that.
My codes:
var DatatableRecordSelectionDemo = function () {
var demo = function () {
var url = '/Data/default.json';
$.getJSON(url, function (data) {
var datatable = $('.m_datatable').mDatatable({
data: {
type: "local",
source: data,
pageSize: 10,
saveState: {
cookie: true,
webstorage: true
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
// layout definition
layout: {
theme: 'default', // datatable theme
"class": '', // custom wrapper class
scroll: false, // enable/disable datatable scroll both horizontal and vertical when needed.
height: 550, // datatable's body's fixed height
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
// columns definition
columns: [{
field: "RecordID",
title: "#",
sortable: false, // disable sort for this column
width: 40,
textAlign: 'center',
selector: { class: 'm-checkbox--solid m-checkbox--brand' }
}, {
field: "OrderID",
title: "Numara",
// sortable: 'asc', // default sort
filterable: true, // disable or enable filtering
// basic templating support for column rendering,
template: '{{OrderID}} - {{ShipCountry}}'
}, {
field: "ShipName",
title: "Adı"
}, {
field: "Status",
title: "Durumu",
// callback function support for column rendering
template: function (row) {
var status = {
true: { 'title': 'Aktif', 'class': ' m-badge--success' },
false: { 'title': 'Pasif', 'class': ' m-badge--danger' }
};
return '<span class="m-badge ' + status[row.Status].class + ' m-badge--wide">' + status[row.Status].title + '</span>';
}
}, {
field: "Actions",
title: "İşlem",
width: 100,
sortable: false,
overflow: 'visible',
template: function (row) {
var tblName = String(row.ShipName).replace(/'/g, "\\'");
var tblid = String(row.RecordID);
return '\
<a href="#" onclick="Modalac('+ tblid + ',\'' + tblName + '\',' + row.Status + ')" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Düzenle">\
<i class="la la-edit"></i>\
</a>\
<a href="#" onclick="Sil('+ tblid + ',\'' + tblName + '\')" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill" title="Sil">\
<i class="la la-trash"></i>\
</a>\
';
}
}]
});
var query = datatable.getDataSourceQuery();
$('#m_form_search').on('keyup', function (e) {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.generalSearch = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(query.generalSearch);
$('#m_form_status').on('change', function () {
// shortcode to datatable.getDataSourceParam('query');
var query = datatable.getDataSourceQuery();
query.Status = $(this).val().toLowerCase();
// shortcode to datatable.setDataSourceParam('query', query);
datatable.setDataSourceQuery(query);
datatable.load();
}).val(typeof query.Status !== 'undefined' ? query.Status : '');
$('#m_form_status').selectpicker();
// on checkbox checked event
$('.m_datatable').on('m-datatable--on-check', function (e, args) {
var count = datatable.setSelectedRecords().getSelectedRecords().length;
$('#m_datatable_selected_number').html(count);
if (count > 0) {
$('#m_datatable_group_action_form').collapse('show');
}
})
.on('m-datatable--on-uncheck m-datatable--on-layout-updated', function (e, args) {
var count = datatable.setSelectedRecords().getSelectedRecords().length;
$('#m_datatable_selected_number').html(count);
if (count === 0) {
$('#m_datatable_group_action_form').collapse('hide');
}
});
$('.m_datatable tbody').on('click', 'tr', function (){
var id = this.RecordID;
var index = $.inArray(id, selected);
if (index === -1)
{
selected.push(id);
} else
{
selected.splice(index, 1);
}
$(this).toggleClass('selected');
});
});
};
return {
// public functions
init: function () {
demo();
}
};
}();
var TopluIslem = function () {
var datatable = $('.m_datatable').mDatatable();
var dataArr = [];
$.each($(".m_datatable tr.selected"),function(){
dataArr.push($(this).find('td').eq(0).text());
});
console.log(dataArr);
alert(rowCount);
};
jQuery(document).ready(function () {
DatatableRecordSelectionDemo.init();
});
İşlem Yap
I solved the problem
var secilenler = [];
$('.m_datatable').on('m-datatable--on-check', function(e, args) {
secilenler.push(args.toString());
}).on('m-datatable--on-uncheck', function (e, args) {
var i = secilenler.indexOf(args.toString());
if(i !== -1) {
secilenler.splice(i, 1);
}
});

My kendo Grid does not display fields by calling webserver

I need help about a kendo grid,
I call a webservice to fill a datasource of the grid. It seems to work fine, but the data are not displayed in the grid.
The webservice call returns 7 records, and in the grid there are 7 rows, but they are empty.
this is the code:
var mime_charset = "application/json; charset=utf-8";
var serverSelectReturnsJSONString = true;
var model_definition = {
id: "ID",
fields: {
customer_id: { type: "number" },
name_customer: { type: "string" },
address_customer: { type: "string" }
}
}
$(document).ready(function () {
var ds = createJSONDataSource();
$("#grid").kendoGrid({
selectable: true,
theme: "metro",
dataSource: ds,
scrollable: true,
pageable: true,
// height: 300,
toolbar: ["save", "cancel"],
columns: ["ID", "Nome", "Indirizzo"],
editable: true
});
ds.read();
});
and this is the function for filling the datasource:
function createJSONDataSource() {
var dataSource = new kendo.data.DataSource({
severFiltering: true,
serverPaging: true,
PageSize: 15,
//batch: true,
transport: {
autoSync: true,
read: {
type: "POST",
url: "WebServices/GetDataTest.asmx/getCustList",
dataType: "json",
contentType: mime_charset
}
},
schema: {
data: function (data) {
if (data) {
if (serverSelectReturnsJSONString)
return $.parseJSON(data.d);
else
return data.d;
}
},
total: function (result) {
if (!result) return 0;
var xxx = result.d;
if (xxx == null) {
return result.length || 0;
}
if (result.d) {
if (serverSelectReturnsJSONString) {
var data = $.parseJSON(result.d);
return data.length || 0;
}
else {
return result.d.TotalRecords || result.d.length || result.length || 0;
}
}
},
model: model_definition
}
});
dataSource.options.schema.parse = function (dataJ) {
var data;
data = $.parseJSON(dataJ.d);
if (data) {
$.each(data, function (i, val) {
$.each(model_definition.fields, function (j, col) {
if (col.type == "date" || col.type == "datetime") {
val[j] = toDate(val[j]);
}
})
});
var ret = { d: JSON.stringify(data) };
return ret;
}
}
dataSource.reader.parse = dataSource.options.schema.parse;
return dataSource;
}
Your columns definition is not correct, it is an array but of objects (not strings). Check documentation here. If should be something like:
columns: [
{ field: "ID" },
{ field: "Nome" },
{ field: " "Indirizzo" }
],

how to display error message in Add/Edit dialogue of jqGrid while checking duplicate username?

I'm checking duplicate username in Add/Edit Action of User Management and handle the code which is as under:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult InsertUser(UserViewModel viewModel)
{
var user = new User
{
UserID = viewModel.UserID,
UserName = viewModel.UserName,
//Password = "123456",
Password = viewModel.Password,
FullName = viewModel.FullName,
Email = viewModel.Email,
CreationDate = DateTime.Now,
IsActive = viewModel.IsActive
};
//Also check here if user already exist, usename shud be unique.
bool isAlreadyExist = new UserManagement().CheckUserName(user.UserName);
if(isAlreadyExist)
{
return Json(false);
}
try
{
new UserManagement().Save(user);
}
catch (Exception)
{
return Json(false);
}
return Json(true);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateUser(UserViewModel viewModel)
{
User user = new UserManagement().GetUserBy(viewModel.UserID);
if (!viewModel.UserName.TrimEnd().Equals(user.UserName.TrimEnd()))
{
bool isAlreadyExist = new UserManagement().CheckUserName(viewModel.UserName);
if (isAlreadyExist)
{
return Json(false);
}
}
user.UserName = viewModel.UserName;
user.Password = viewModel.Password;
user.FullName = viewModel.FullName;
user.Email = viewModel.Email;
user.IsActive = viewModel.IsActive;
try
{
new UserManagement().Save(user);
}
catch
{
return Json(false);
}
return Json(true);
}
The script code in .cshtml is as under:
<script type="text/javascript">
var arrayIds = [];
var roleDropDown = "";
$(document).ready(function () {
$(".ui-dropdownchecklist > div > div > .active").live("change", function () {
var parentId = $(this).parent().parent().parent().attr("Id");
parentId = parentId.substring(0, parentId.length - 4);
$("#" + parentId + " > span > span").text("Assigning...").css("color", "#666666");
//Set Variable to identify Assign or Deassign Role to User
var checked = false;
if ($(this).attr("checked") == "checked") {
checked = true;
}
//Set RoleId
var role = $(this).val();
//Set UserId
var user = $(this).attr('id');
//Start Ajax Call
$.ajax({
url: '#Url.Action("ManageUserRoles", "Role")',
type: "GET",
cache: false,
data: { userid: user, roleid: role, chked: checked },
//async: false,
success: function () {
},
complete: function () {
$("#" + parentId + " > span > span").text("Assign Roles").css("color", "#222222");
}
});
//End Ajax Call
});
roleDropDown = "<select id='_RoleID' multiple='true' style='Display: none;'>";
$.ajax({
url: '#Url.Action("GetAllReoles", "Role")',
type: "GET",
cache: true,
async: false,
success: function (countiesJson) {
$.each(countiesJson, function (index, optionData) {
roleDropDown += "<option value='" + optionData.RoleID + "'>" + optionData.RoleName + "</option>";
});
}
});
roleDropDown += "</select>";
var userGrid = $('#jqgUsers');
var pages = [];
var MAX_PAGERS = 2;
$('#jqgUsers').jqGrid({
//url from wich data should be requested
url: '#Url.Action("FetchUsers")',
//type of data
datatype: 'json',
cache: false,
//url access method type
mtype: 'POST',
postData: {
UserName: function () { return $('#UserName1').val(); },
FullName: function () { return $('#FullName1').val(); },
Email: function () { return $('#Email1').val(); },
IsActive: function () { return $('#IsActive1 option:selected').val(); },
FromDate: function () { return $('#FromDate').val(); },
ToDate: function () { return $('#ToDate').val(); }
},
colNames: ['User ID', 'User Name', 'Password', 'Full Name', 'Email', 'Active', 'Roles', ''],
//columns model
colModel: [
{ name: 'UserID', index: 'UserID', hidden: true, align: 'left', editable: false },
{ name: 'UserName', index: 'UserName', width: 252, align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 50 }, editrules: { required: true} },
{ name: 'Password', index: 'Password', hidden: true, width: 175, align: 'left', editable: true, edittype: 'password', editoptions: { maxlength: 20 }, editrules: { required: true, edithidden: true} },
{ name: 'FullName', index: 'FullName', width: 245, align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 100 }, editrules: { required: true} },
{ name: 'Email', index: 'Email', width: 247, align: 'left', formatter: emailFormatter, sortable: true, editable: true, edittype: 'custom', editoptions: { custom_element: mymailelem, custom_value: mymailvalue }, editrules: { required: true, email: true} },
{ name: 'IsActive', index: 'IsActive', width: 85, formatter: imgformatter, sortable: true, align: 'center',
editable: true, edittype: 'custom', editoptions: { custom_element: myelem, custom_value: myvalue }
},
{ name: 'role', index: 'role', width: 120, formatter: RoleCobFormatter, sortable: true, align: 'left' },
{ name: 'act', index: 'act', width: 55, align: 'center', sortable: false, formatter: 'actions',
formatoptions: {
keys: true,
editformbutton: true,
delbutton: true,
editOptions: {
url: '#Url.Action("UpdateUser")',
closeAfterEdit: true
},
delOptions: {
url: '#Url.Action("DeleteUser")'
}
}
}
],
pager: $('#jqgpUsers'),
rowNum: 10,
pginput: false,
rowList: [10, 20, 50, 100],
sortname: 'UserID',
sortorder: 'asc',
viewrecords: true,
height: 'auto',
loadComplete: function () {
if (pages[$('#jqgUsers').getGridParam('page')] != null) {
var selRows = pages[$('#jqgUsers').getGridParam('page')];
var i;
var limit = selRows.length;
for (i = 0; i < limit; i++) {
$('#jqgUsers').setSelection(selRows[i], true);
}
}
//-------Start Paging Style
var i, myPageRefresh = function (e) {
var newPage = $(e.target).text();
userGrid.trigger("reloadGrid", [{ page: newPage}]);
e.preventDefault();
};
//variables
var currentPage = this.p.page;
var startPage;
var totalPages = this.p.lastpage;
if (this.p.records == 0) {
totalPages = 0;
}
if (this.p.page - MAX_PAGERS <= 0) {
startPage = 1;
}
else {
startPage = this.p.page - MAX_PAGERS;
}
var lastPage;
if (this.p.page + MAX_PAGERS >= totalPages) {
lastPage = totalPages;
}
else {
lastPage = this.p.page + MAX_PAGERS;
}
$(userGrid[0].p.pager + '_center td.myPager').remove();
//---- Variables End
if (totalPages > 1) {
var pagerPrevTD = $('<td>', { "class": "myPager" }), prevPagesIncluded = 0,
pagerNextTD = $('<td>', { "class": "myPager" }), nextPagesIncluded = 0,
totalStyle = userGrid[0].p.pginput === false,
startIndex = totalStyle ? this.p.page - MAX_PAGERS * 2 : this.p.page - MAX_PAGERS;
for (i = startPage; i <= lastPage; i++) {
if (i <= 0) { continue; }
var link = $('<a>', { href: '#', click: myPageRefresh, "class": "Paging" });
if (i == this.p.page) { link.attr("class", "selected"); }
link.text(String(i));
if (i < this.p.page || totalStyle) {
pagerPrevTD.append(link);
prevPagesIncluded++;
} else {
if (nextPagesIncluded > 0 || (totalStyle && prevPagesIncluded > 0)) { pagerNextTD.append('<span>, </span>'); }
pagerNextTD.append(link);
nextPagesIncluded++;
}
}
if (prevPagesIncluded > 0) {
$(userGrid[0].p.pager + '_center td[id^="prev"]').after(pagerPrevTD);
}
if (nextPagesIncluded > 0) {
$(userGrid[0].p.pager + '_center td[id^="next"]').before(pagerNextTD);
}
}
else {
//$('#first_jqgpFlagger').unbind();
$('#first_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
//$('#prev_jqgpFlagger').unbind();
$('#prev_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
//$('#next_jqgpFlagger').unbind();
$('#next_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
//$('#last_jqgpFlagger').unbind();
$('#last_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
}
//-------End Paging Style
},
gridComplete: function () {
$.each(arrayIds, function (index, optionData) {
$.ajax({
url: '#Url.Action("GetRolesbyUserId", "Role")' + '/' + optionData.substring(4),
type: "GET",
cache: false,
async: false,
success: function (countiesJson) {
$.each(countiesJson, function (index, optionItem) {
$("#" + optionData + " option[value='" + optionItem.RoleID.toString() + "']").attr("selected", "selected");
});
}
});
if ($("#ddcl-" + optionData).length > 0) {
$("#ddcl-" + optionData).remove();
$("#ddcl-" + optionData + "-ddw").remove();
}
$("#" + optionData).dropdownchecklist({ emptyText: "Assign Roles" });
}); //End Each Loop
}
});
$('#jqgUsers').jqGrid('navGrid', '#jqgpUsers',
{ add: true, del: false, edit: false, search: false },
{ width: '250', closeAfterEdit: true, url: '#Url.Action("UpdateUser")' },
{ width: '250', closeAfterAdd: true, url: '#Url.Action("InsertUser")' },
{ width: '250', url: '#Url.Action("DeleteUser")' });
$('#CustomPanel').appendTo('.ui-jqgrid-hbox');
$(".ui-jqgrid-sortable").attr("style", "height: 32px");
$('#UserName1').blur(function () {
$('#jqgUsers').trigger("reloadGrid");
});
$('#FullName1').blur(function () {
$('#jqgUsers').trigger("reloadGrid");
});
$('#Email1').blur(function () {
$('#jqgUsers').trigger("reloadGrid");
});
$('#IsActive1').change(function () {
$('#jqgUsers').trigger("reloadGrid");
});
$('#btnClear').click(function () {
$('#UserName1').val('');
$('#FullName1').val('');
$('#Email1').val('');
$('#IsActive1 option:eq(0)').attr('selected', 'selected');
$('#jqgUsers').trigger("reloadGrid");
});
});
function emailFormatter(cellvalue) {
email = "<a href='mailto:" + cellvalue + "'>" + cellvalue + "</a>";
return email;
}
function mymailelem(value, options) {
var e1 = document.createElement("input");
e1.type = "text";
if (value != "") {
value = value.split('>')[1].split('<')[0];
}
e1.value = value;
z = document.createAttribute('class');
z.value = 'FormElement ui-widget-content ui-corner-all';
e1.setAttributeNode(z);
return e1;
}
function mymailvalue(elem, operation, value) {
if (value != undefined) {
value = value.split('>')[1].split('<')[0];
}
else {
value = '';
}
if (operation === 'get') {
return $(elem)[0].value;
} else if (operation === 'set') {
$(elem).val(value);
}
}
function imgformatter(cellvalue, options, rowObject) {
if (cellvalue == 'True') {
ActiveImage = "<img border='0' src='../../Content/images/tick.png' alt='' width='16px' height='16px' style='padding-top: 7px;' />";
}
else {
ActiveImage = "<img border='0' src='../../Content/images/cross.png' alt='' width='16px' height='16px' style='padding-top: 7px;' />";
}
return ActiveImage;
}
function RoleCobFormatter(cellvalue, options, rowObject) {
var id = "sel-" + options.rowId.toString();
arrayIds.push(id);
var retVal = roleDropDown.replace('_RoleID', id);
return retVal;
}
function myelem(value, options) {
var el = document.createElement("input");
el.type = "checkbox";
if (value.indexOf('tick') != -1) {
value = 'checked';
el.checked = 'checked';
}
else {
value = '';
el.checked = '';
}
return el;
}
function myvalue(elem, operation, value) {
if (value != undefined && value.indexOf('tick') != -1) {
value = 'checked';
}
else {
value = '';
}
if (operation === 'get') {
// return $(elem).find("input").val();
return $(elem).is(':checked');
} else if (operation === 'set') {
// $('input', elem).val(value);
// $('input', elem).attr('checked', value);
$(elem)[0].checked = value;
}
}
</script>
How can i display error message in Add/Edit Dialogue, please suggest.
the correct way will be to use some error HTML code in case of error. Instead of catching all exception in the server cage and returns return Json(false) you can throw exception which contains an error message. You can use [HandleJsonException] for example (see the answer) to encode any exceptions as simple JSON response with System.Net.HttpStatusCode.InternalServerError as HttpContext.Response.StatusCode. In the way you can post detailed error information to the jqGrid.
To decode the error information you can use errorTextFormat method in the same way as in decodeErrorMessage function from the same answer.
If you follow the way you will don't need to use any CheckUserName method. instead of that you can use method like .Save(user). The exception will be thrown automatically if needed. If you want to display more detailed error information you can catch for example SqlException, decode the information and produce another exception in the text of which you just includes information from the Server, Procedure, LineNumber, Message and so on properties of SqlException.

Resources