How to validate select2? - jquery-select2

I have a select2 as below:
<select class="form-select" id="ds" name="ds" tabindex="1" required></select>
I populate it using:
var data = [{ id: "0", text: "" }, { id: "1", text: "List" }, { id: "2", text: "Tags" }];
$('#ds').select2({
data: data
})
I try to validate it using below, but it's not working, what did I do wrong?
$form.each(function() {
var $this = $(this);
$this.validate({
rules: {
data_source: {
required: true
}
},
messages: {
data_source: {
required: 'Data source field is required'
}
}
});
});

Related

jquery select2 return json result name

I am new in jquery select2, in result return id, text and name where id is value I know how to get return id(value) with x$("inputBox").val();. but I want get return name in jquery-select2.
Is there any method to get the return name?
x$("#{id:city_combo_box}").select2({
placeholder:"Select City",
allowClear:true,
minimuminputLength:2,
templateResult: formatRepo,
escapeMarkup: function (markup) {return markup},
templateSelection: formatRepoSelection,
multiple:false,
ajax: {
url:ajaxurl,
dataType:"json",
data: function(params){
pp = params.term;
return{
startKey: pp,
page: params.page,
count: 10
};
},
processResults: function (data, params){
var k = data.viewentry;
console.log(k);
params.page = params.page;
return {
results: $.map(k, function(obj) {
return {id: (obj.entrydata[1].text[0]), text: obj.entrydata, name: (obj.entrydata[0].text[0])};
})
};
}
}
}).on("change", function(e){ x$("#{id:claim_limit_text}").val(x$("#{id:city_combo_box}").val(id));
}).trigger("change");
})
The only solution I came across is this:
html
<div id="ddWrapper1">
<select id="dd1"></select>
</div>
js
$(document).ready(function() {
var ddDate = [{
id: 1,
text: 'some item'
}, {
id: 2,
text: 'even more items'
}, {
id: 3,
text: 'oh no'
}, {
id: 4,
text: 'that is a realy long item name...'
}];
$('#dd1').select2({
data: ddDate,
allowClear: true,
multiple: true,
placeholder: '[dd1] select some items'
});
$('#dd1').on('change', function() {
console.log($('#dd1').data('select2').$selection[0].innerText);
})
});
But I have to admit that the result is not the nicest.

Kendo MVC Grid paging buttons not changing results displayed

I have a Kendo Grid. The paging numbers are ok, items per page is ok, but when I press on page number the results in grid isn't changing, all results are shown in first page. Please help here.
Below is my code:
<script>
$(function() {
$("#invoices-grid").kendoGrid({
dataSource: {
data: #Html.Raw(JsonConvert.SerializeObject(Model.Invoices)),
schema: {
model: {
fields: {
JobNumber: { type: "string" },
CustomerName: { type: "string" },
DepartmentName: { type: "string" },
DateInvoice: { type: "string" },
ValidDays: { type: "number" },
Delivery: { type: "string" },
IsPayed: { type: "boolean" },
Payed: { type: "number" },
Status: { type: "boolean" },
}
}
},
#*type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("List", "Finances"))",
type: "POST",
dataType: "json",
data: additionalData1
},
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},*#
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
columns: [
{
field: "JobNumber",
title: "#T("gp.Invoice.Fields.JobNumber")",
template: '#= JobNumber #'
},
{
field: "CustomerName",
title: "#T("gp.Invoice.Fields.CustomerName")",
template: '#= CustomerName #'
},
{
field: "DepartmentName",
title: "#T("gp.Invoice.Fields.DepartmentName")",
template: '#= DepartmentName #'
},
{
field: "DateInvoice",
title: "#T("gp.Invoice.Fields.DateInvoice")",
template: '#= DateInvoice #'
},
{
field: "ValidDays",
title: "#T("gp.Invoice.Fields.ValidDays")",
template: '#= ValidDays #'
},
{
field: "Delivery",
title: "#T("gp.Invoice.Fields.Delivery")",
template: '#= Delivery #'
},
{
field: "Payed",
title: "#T("gp.Invoice.Fields.IsPayed")",
template: '#= (Payed == 2) ? "Комп." : ((Payed == 1) ? "ДЕ" : "НЕ") #'
},
{
field: "Id",
title: "#T("Common.Edit")",
width: 100,
template: '#T("Common.Edit")'
},
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "popup"
},
scrollable: false,
selectable: true,
change: function(e) {
var selectedRows = this.select();
var jobId = parseInt($(selectedRows).data('job-id'));
var jobItemId = parseInt($(selectedRows).data('job-item-id'));
var result = $.get("#Url.Action("SideDetails", "Production")/" + jobItemId);
result.done(function(data) {
if (data) {
$(".job-edit .jobItemDetails").html(data);
}
});
},
rowTemplate: kendo.template($("#invoiceRowTemplate").html()),
});
});
</script>
protected virtual void PrepareInvoiceFinanceListModel(FinanceListModel model,FormCollection form/*,string SearchJobItemNumber*/)
{
var customers = model.SearchCustomerId;
var isChecked = model.IsChecked;
var searchString = model.SearchJobItemNumber;
var IsChecked1 = model.IsChecked1;
// searchString = model.SearchJobItemNumber;/* "001/2016";*/
//var searchString = model.SearchJobItemNumber;
//searchString = "091/2016";
if (model == null)
throw new ArgumentNullException("model");
var finishedJobs = _jobService.GetJobsByHasInvoice(false);
finishedJobs = finishedJobs.OrderByDescending(x =>
{
var firstOrDefault = x.JobItems.FirstOrDefault();
return firstOrDefault?.DateCompletition ?? new DateTime();
}).ToList();
foreach (var job in finishedJobs)
{
var jobModel = job.ToModel();
model.FinishedJobs.Add(jobModel);
}
var jobsBycustomers = finishedJobs.GroupBy(x => new { x.CustomerId, x.Customer.Name }).Select(x => new JobCustomersModel()
{
CustomerId = x.Key.CustomerId,
CustomerName = x.Key.Name,
JobsCount = x.Count(),
});
model.FinishedJobStatus = new JobStatusesModel()
{
Status = _localizationService.GetResource("gp.jobs.whitout.invoice"),
Value = (int)JobStatusEnum.Finished,
Count = finishedJobs.Count,
CustomersJobs = jobsBycustomers.ToList()
};
var invoices = _invoiceService.GetAllInvoices(searchString, isChecked, IsChecked1, customers);
foreach (var invoice in invoices)
{
var inv = invoice.ToModel();
// var a = invoice.Payed;
model.Invoices.Add(inv);
}
///////////////////// ////////////////////////
//var allCustomers = _invoiceService.GetAllCustomers(customers);
//foreach (var customer in allCustomers)
//{
// var cust = customer.ToModel();
// model.SearchCustomerId = customer.CustomerId;
// model.Invoices.Add(cust);
//}
var invoiceByCustomer = invoices
.GroupBy(x => new { x.CustomerId, x.CustomerName })
.Select(x => new JobCustomersModel()
{
CustomerId = x.Key.CustomerId,
CustomerName = x.Key.CustomerName,
JobsCount = x.Count(),
});
model.InvoiceStatus = new JobStatusesModel()
{
Status = _localizationService.GetResource("gp.jobs.with.invoice"),
Value = (int)JobStatusEnum.Finished,
Count = invoices.Count,
CustomersJobs = invoiceByCustomer.ToList()
};
var latestOffers = _offerService.GetLatestOffers(0, 10);
foreach (var offer in latestOffers)
{
var offerModel = offer.ToModel();
model.LatestOffers.Add(offerModel);
}
}
Currently server operations are enabled...
serverPaging: true,
serverFiltering: true,
serverSorting: true
... but the transport configuration is commented out. This is the cause of the problem.
If you want to use server operations, then configure the dataSource transport. Otherwise, use local data binding and disable server operations, as in this example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.3.914/styles/kendo.default.min.css">
<script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>
</head>
<body>
<div id="invoices-grid"></div>
<script>
$(function() {
var d = [];
for (var i = 1; i <= 100; i++) {
d.push({Id: i, CustomerName: "CustomerName " + i});
}
$("#invoices-grid").kendoGrid({
dataSource: {
data: d,
schema: {
model: {
id: "Id",
fields: {
CustomerName: { type: "string" }
}
}
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
//serverPaging: true,
//serverFiltering: true,
//serverSorting: true
},
columns: [
{
field: "CustomerName",
title: "gp.Invoice.Fields.CustomerName",
template: '#= CustomerName #'
},
{
field: "Id",
title: "Common.Edit",
width: 100,
template: 'Common.Edit'
},
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "popup"
},
scrollable: false,
selectable: true,
change: function(e) {
}
});
});
</script>
</body>
</html>

Bind results from search

I cannot bind results from search in kendo grid. I've tried many times, I'm in trouble four days, I don't know what is wrong here,
When i debug action everything is working perfect,data is OK, return grid result are OK, but results aren't shown in kendo.
Here is my code:
<script>
$(function() {
$("a.k-button").on('click', function (e) {
debugger;
e.preventDefault();
var dataObj = serializeByFieldsWrap(".invoiceForm");
var dataUrl = $(this).data('url');
// dataObj.ToolboxId = toolboxId;
$('body').css('cursor', 'wait');
var result = $.ajax({
type: "POST",
url: dataUrl,
dataType: 'json',
data: dataObj,
//complete: $("#invoices-grid").data("kendoGrid").data.read(),
});
result.done(function (data) {
console.log(data);
var grid = $('#invoices-grid').data("kendoGrid");
grid.dataSource.data(data);
});
result.fail(function (error) {
console.log(error);
});
});
});
</script>
Controller:
public ActionResult List(DataSourceRequest command, FinanceListModel model)
{
var searchString = model.SearchJobItemNumber;
var isChecked = model.IsChecked;
var invoices = _invoiceService.GetAllInvoices(searchString, isChecked);
var gridModel = new DataSourceResult
{
Data = invoices.Select(x => {
var jobModel = x.ToModel();
return jobModel;
}),
Total = invoices.TotalCount
};
return Json(gridModel, "application/json", JsonRequestBehavior.AllowGet);
}
Kendo UI Grid:
<script>
$(function() {
$("#invoices-grid").kendoGrid({
dataSource: {
data: #Html.Raw(JsonConvert.SerializeObject(Model.Invoices)),
schema: {
model: {
fields: {
JobNumber: { type: "string" },
CustomerName: { type: "string" },
DepartmentName: { type: "string" },
DateInvoice: { type: "string" },
ValidDays: { type: "number" },
Delivery: { type: "string" },
IsPayed: { type: "boolean" },
Payed: { type: "number" },
Status: { type: "boolean" },
},
error: function(e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
dataBound: function () {
var row = this.element.find('tbody tr:first');
this.select(row);
},
columns: [
#*{
field: "Status",
title: "#T("gp.Jobs.Fields.Status")",
template: '#= Status #'
},*#
{
field: "JobNumber",
title: "#T("gp.Invoice.Fields.JobNumber")",
template: '#= JobNumber #'
},
{
field: "CustomerName",
title: "#T("gp.Invoice.Fields.CustomerName")",
template: '#= CustomerName #'
},
{
field: "DepartmentName",
title: "#T("gp.Invoice.Fields.DepartmentName")",
template: '#= DepartmentName #'
},
{
field: "DateInvoice",
title: "#T("gp.Invoice.Fields.DateInvoice")",
template: '#= DateInvoice #'
},
{
field: "ValidDays",
title: "#T("gp.Invoice.Fields.ValidDays")",
template: '#= ValidDays #'
},
{
field: "Delivery",
title: "#T("gp.Invoice.Fields.Delivery")",
template: '#= Delivery #'
},
{
field: "Payed",
title: "#T("gp.Invoice.Fields.IsPayed")",
template: '#= (Payed == 2) ? "Комп." : ((Payed == 1) ? "ДЕ" : "НЕ") #'
},
{
field: "Id",
title: "#T("Common.Edit")",
width: 100,
template: '#T("Common.Edit")'
}
],
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50]
},
editable: {
confirmation: false,
mode: "popup"
},
scrollable: false,
selectable: true,
change: function(e) {
var selectedRows = this.select();
var jobId = parseInt($(selectedRows).data('job-id'));
var jobItemId = parseInt($(selectedRows).data('job-item-id'));
var result = $.get("#Url.Action("SideDetails", "Production")/" + jobItemId);
result.done(function(data) {
if (data) {
$(".job-edit .jobItemDetails").html(data);
}
});
},
rowTemplate: kendo.template($("#invoiceRowTemplate").html()),
});
});
</script>
DataSourceResult formats your server response like this:
{
Data: [ {JobNumber: "...", FieldName: "bar", ... } ],
Total: 100
}
In other words, the data items array is assigned to a Data field, and the total items count is assigned to a Total field. The Kendo UI DataSource configuration must take this into account by setting schema.data and schema.total:
http://docs.telerik.com/kendo-ui/framework/datasource/crud#schema
http://docs.telerik.com/kendo-ui/framework/datasource/crud#read-remote
schema: {
data: "Data",
total: "Total"
}

Kendo UI Upload inside Grid

I am trying to implement Kendo UI Grid with an Kendo Upload inside the grid. While I am using ASP.NET MVC I am not using the Telerik MVC Wrappers. I am attempting to do this without them.
The problem that I am having is that IEnumerable HttpPostedFileBase is null when it posts back to my Action method.
JavaScript:
$(document).ready(function () {
var dsGalleryItemFile = new kendo.data.DataSource({
transport: {
read: "#Url.Content("~/Intranet/GalleryItemFile/ListFiles/")#Model.galleryItemID",
update: {
url: "#Url.Content("~/Intranet/GalleryItemFile/UpdateFile")",
type: "POST"
},
destroy: {
url: "#Url.Content("~/Intranet/GalleryItemFile/DeleteFile")",
type: "POST"
},
create: {
url: "#Url.Content("~/Intranet/GalleryItemFile/CreateFile/")#Model.galleryItemID",
type: "POST"
}
},
// determines if changes will be send to the server individually or as batch
batch: false,
schema: {
model: {
id: "fileID",
fields: {
fileID: {
editable: false,
nullable: true
},
filename: {},
fileType: { defaultValue: {fileTypeID: 1, fileType: "Web JPEG"} },
fileType: {},
width: { type: "number" },
height: { type: "number" },
}
}
}
});
$("#gvGalleryItemFile").kendoGrid({
columns: [{
field: "filename",
title: "Filename"
}, {
field: "filepath",
title: "File Upload",
editor: fileUploadEditor//,
//template: "<img src='#=filepath.filepath#' />"
}, {
field: "fileType",
title: "File Type",
editor: fileTypeDropDownEditor,
template: "#=fileType.fileType#",
}, {
field: "width",
title: "Width"
}, {
field: "height",
title: "Height"
}, {
command: ["edit", "destroy"]
}],
editable: { mode: "inline" },
toolbar: ["create"],
dataSource: dsGalleryItemFile
});
});
function fileTypeDropDownEditor(container, options) {
$('<input required data-text-field="fileType" data-value-field="fileTypeID" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: {
transport: {
read: "#Url.Content("~/Intranet/FileType/ListFileTypes")"
}
}
});
}
function fileUploadEditor(container, options) {
$('<input type="file" name="fileUpload" id="fileUpload" />')
.appendTo(container)
.kendoUpload({
async: {
saveUrl: "#Url.Content("~/Intranet/GalleryItemFile/UploadFile")"
},
complete: onUploadComplete
});
}
MVC Action:
[HttpPost]
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> uploadedFiles)
{
if (uploadedFiles != null)
{
foreach (var thisFile in uploadedFiles)
{
string newFileName = Path.GetFileName(thisFile.FileName).Replace(" ", "");
var physicalPath = Path.Combine(Server.MapPath("~/Areas/Gallery/Content/GalleryImages"), newFileName);
thisFile.SaveAs(physicalPath);
}
return Content("");
}
else
{
return Content("Error");
}
}
Try to name the argument parameter in the action method signature the same way as the name attribute of the input that you turn into upload widget.
In your case
public ActionResult UploadFile(IEnumerable<HttpPostedFileBase> fileUpload)

Kendo.Web Grid Popup Create with ComboBox

I am using the free Kendo web controls. I have used the grid view in several places before and decided to use the popup style editing for my current project.
I have most of it working. I have three combo boxes for category, bank account and payee and when I edit an existing item, the model object passed back to my MVC action has the correct values in it. However, when I click on the create button, the three combo box values are returned as null to the controller.
Here is the CSHTML code for this view:
#using System
#using System.Linq
#{
ViewBag.Title = "Transactions";
}
#section Head
{
<link href="~/Content/kendo/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/kendo.web.min.js"> </script>
}
#section featured
{
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title</h1>
</hgroup>
</div>
</section>
}
<div id="grid"></div>
<script>
$(function() {
$("#grid").kendoGrid({
height: 350,
toolbar: [{ name: "create", text: "Create New Transaction" }],
columns:
[
{ field: "Date", width: "100px", template: '#= kendo.toString(Date,"MM/dd/yyyy") #' },
{ field: "Amount", format: "{0:c}", width: "100px" },
{ field: "Category", width: "80px", editor: categoryDropDownEditor, template: "#=Category.Name#" },
{ field: "BankAccount", title: "Account", width: "80px", editor: bankAccountDropDownEditor, template: "#=BankAccount.Name#" },
{ field: "Payee", width: "80px", editor: payeeDropDownEditor, template: "#=Payee.Name#" },
{ command: ["edit", "destroy"], title: " ", width: "160px" }
],
editable: { mode: "popup", confirmation: "Are you sure you want to delete this transaction?" },
pageable:
{
refresh: true,
pageSizes: true
},
sortable: true,
filterable: false,
dataSource:
{
serverPaging: true,
serverFiltering: true,
serverSorting: true,
pageSize: 7,
schema:
{
data: "Data",
total: "Total",
model:
{
id: "Id",
fields:
{
Id: { editable: false, nullable: true },
Date: { type: "Date" },
Amount: { type: "number", validation: { required: true, min: 0 } },
Category: { validation: { required: true } },
BankAccount: { validation: { required: true } },
Payee: { validation: { required: true } },
Note: { validation: { required: false } }
}
}
},
batch: false,
transport:
{
create:
{
url: "#Url.Action("Create", "Transaction")",
contentType: "application/json",
type: "POST"
},
read:
{
url: "#Url.Action("Read", "Transaction")",
contentType: "application/json",
type: "POST"
},
update:
{
url: "#Url.Action("Update", "Transaction")",
contentType: "application/json",
type: "POST"
},
destroy:
{
url: "#Url.Action("Delete", "Transaction")",
contentType: "application/json",
type: "POST"
},
parameterMap: function(data)
{
return JSON.stringify(data);
}
}
}
});
function categoryDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetCategories", "Transaction")" }
}
});
}
function bankAccountDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetBankAccounts", "Transaction")" }
}
});
}
function payeeDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetPayees", "Transaction")" }
}
});
}
});
</script>
The binding to the kendo combo box must be working, otherwise the edit would fail as well. All I can think is that the object is not created correctly. Also, it selects the first item in the combo box by default, but even so, does not bind the value.
Following is the code for my create and update actions:
[HttpPost]
public ActionResult Create(TransactionModel transactionModel)
{
var transaction = _moneyBO.CreateTransaction();
Mapper.Map(transactionModel, transaction);
_moneyBO.UpdateTransaction(transaction);
return Json(Mapper.Map<TransactionModel>(transaction));
}
public ActionResult Update(TransactionModel transactionModel)
{
var transaction = _moneyBO.Transactions.SingleOrDefault(x => x.Id == transactionModel.Id);
if (transaction == null)
return View("NotFound");
Mapper.Map(transactionModel, transaction);
_moneyBO.UpdateTransaction(transaction);
return Json(Mapper.Map<TransactionModel>(transaction));
}
I have not found a good example using the popup custom edit. The example on the Kendo site works inline, but if you change the example to popup it does not work.
I have a same problem. Write, if you solve it, please
I found, that Kendo think that "null" (default for int?) is ObservableObject (while initialization of ComboBox), thats why it can't be parsed to "number". If you edit item (not create), value id not "null" and model bindind work's fine
Not sure if it's the only issue here but in your code example it looks like the initialization of your dropdown isn't quite correct. You have written dataValueFileld which should be dataValueField
kendoDropDownList({
autoBind: true,
dataValueFileld: "Id", <-- Incorrect spelling
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetPayees", "Transaction")" }
}
});

Resources