How to work with enum in kendo grid - javascript

Sorry for my English.
I have an enum and my grid display only numeric values. How can I work only with text variant of enum? This is quite a common problem, but I still have not found a suitable solution for me.
I will be glad to any help with this issue)
Index.cshtml
#{
ViewBag.Title = "Book List";
}
<script type="text/kendo" id="authorsTemplate">
<ul>
# for(var i = 0; i < Authors.length; i++){ #
<li>#: Authors[i].AuthorName #</li>
# } #
</ul>
</script>
<div id="grid"></div>
<script>
function authorsEditor(container, options) {
$('<input name="Authors">').appendTo(container)
.kendoMultiSelect({
dataValueField: "AuthorId",
dataTextField: "AuthorName",
dataSource: #Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewData["authors"]))
});
}
$("#grid").kendoGrid({
pageable: true,
toolbar: ["create"],
dataSource: {
pageSize: 3,
transport: {
read: {
url: "#Url.Action("Read", "Grid")",
type: "POST"
},
update: {
url: "#Url.Action("Update", "Grid")",
contentType: "application/json",
type: "POST"
},
create: {
url: "#Url.Action("Create", "Grid")",
contentType: "application/json",//hz nado li
type: "POST"
},
destroy: {
url: "#Url.Action("Destroy", "Grid")",
contentType: "application/json",//hz nado li
type: "POST"
},
parameterMap: function(options) {
return kendo.stringify(options);
}
},
schema: {
model: {
id: "BookId",
fields: {
AuthorName: { type: "string" }
}
}
}
},
editable: "inline",
columns: [
"BookName",
"Pages",
// { editor: GenreEditor, field: "Genre" },IEnumerable<Number2.Models.AuthorViewModel>
"Genre",
"Publisher",
{
editor: authorsEditor, field: "Authors", template: $("#authorsTemplate").html()
},
{ command: ["edit", "destroy"] }
]
});
</script>
ViewModel and Enum(typical viewmodel and enum)
namespace Number2.Models
{
public class BookViewModel
{
public BookViewModel()
{
Authors = new List<AuthorViewModel>();
}
[ScaffoldColumn(false)]
public int BookId { get; set; }
[Display(Name = "Book Name")]
[MaxLength(100, ErrorMessage = "Book Name must be 100 characters or less"), MinLength(5)]
public string BookName { get; set; }
public int Pages { get; set; }
public string Publisher { get; set; }
[Range(0, maximum: 10)]
public Genre Genre { get; set; }
[UIHint("AuthorsEditor")]
public virtual List<AuthorViewModel> Authors { get; set; }
public void CopyToBook(Book book)
{
book.BookId = BookId;
book.BookName = BookName;
book.Pages = Pages;
book.Genre = Genre;
book.Publisher = Publisher;
}
}
public enum Genre
{
[Description("Comedy")]
Comedy,
[Description("Drama")]
Drama,
[Description("Horror")]
Horror,
[Description("Realism")]
Realism,
[Description("Romance")]
Romance,
[Description("Satire")]
Satire,
[Description("Tragedy")]
Tragedy,
[Description("Tragicomedy")]
Tragicomedy,
[Description("Fantasy")]
Fantasy,
[Description("Mythology")]
Mythology,
[Description("Adventure")]
Adventure,
}
}
Question is still relevant...
I think there is should use special viewmodel for my enum, but i dunno how can i do it correctly.

Related

How to post a complicated url request using ajax

I want to do a ajax post to a label printing API using string like this, but seems there are syntax error or something wrong, please give to some directions, thanks.
This is for a web API to printing labels.
Below are javascript codes in Asp.Net MVC5 view page.
url like this:
var urlString = "http://localhost:3112/PrintService?REQUEST_DATA={
"PRINT_REQUEST": {
"PRINT_NAME": "TSC TTP-345 (TEST)",
"LABEL_QTY": 1,
"TEMPLATE_PATH": "WD.LAB",
"PRINT_DATA": [
{
"storage": "",
"SPEC": "",
"ITEM": "",
"QTY": "500",
"DEMAND": "0",
"EXP_DATE1": "2021-05-21",
"EXP_DATE2": "2021-05-21",
"ALLERGENS": "",
"WD_DATE": "2019-10-29 23:59:59",
"WD_USER": "TEST",
"WD_USER_NAME": "TEST",
"TCI_LOTNO": "20190522",
"SHOP_ORDER": "",
"SHOP_ORDER_ITEM": "",
"SHOP_ORDER_DESC": "",
"SPLIT_SFC_COUNT": "",
"SUP_LOTNO": "",
"REPRINT": null,
"PACKCOUNT": "",
"SFC": "",
"WEIGHT": "",
"PCS": "",
"SKIN_WEIGHT": -500
}
]
}
}";
ajax like this:
$.ajax({
type: "POST",
url: urlString,
data: {
},
dataType: 'html',
success: function (ret) {
labeldata = ret;
window.alert("OK");
},
error: function (ret) {
window.alert(ret);
}
})
Use encodeURI():
var url = 'http://localhost:3112/PrintService?REQUEST_DATA={ "PRINT_REQUEST": { "PRINT_NAME": "TSC TTP-345 (TEST)", "LABEL_QTY": 1, "TEMPLATE_PATH": "WD.LAB", "PRINT_DATA": [ { "storage": "", "SPEC": "", "ITEM": "", "QTY": "500", "DEMAND": "0", "EXP_DATE1": "2021-05-21", "EXP_DATE2": "2021-05-21", "ALLERGENS": "", "WD_DATE": "2019-10-29 23:59:59", "WD_USER": "TEST", "WD_USER_NAME": "TEST", "TCI_LOTNO": "20190522", "SHOP_ORDER": "", "SHOP_ORDER_ITEM": "", "SHOP_ORDER_DESC": "", "SPLIT_SFC_COUNT": "", "SUP_LOTNO": "", "REPRINT": null, "PACKCOUNT": "", "SFC": "", "WEIGHT": "", "PCS": "", "SKIN_WEIGHT": -500 } ] } }';
url=encodeURI(url);
console.log(url);
$.ajax({
type: "POST",
url: url,
data: {
},
dataType: 'html',
success: function (ret) {
labeldata = ret;
window.alert("OK");
},
error: function (ret) {
window.alert(ret);
}
})
You should put this string without URL inside data section, you can't use it like this.
you can create one modal and you can pass it in controller as below.
var url = 'http://localhost:3112/PrintService';
var model = {
"PRINT_REQUEST": {
"PRINT_NAME": "TSC TTP-345 (TEST)",
"LABEL_QTY": 1,
"TEMPLATE_PATH": "WD.LAB",
"PRINT_DATA": [
{
"storage": "",
"SPEC": "",
"ITEM": "",
"QTY": "500",
"DEMAND": "0",
"EXP_DATE1": "2021-05-21",
"EXP_DATE2": "2021-05-21",
"ALLERGENS": "",
"WD_DATE": "2019-10-29 23:59:59",
"WD_USER": "TEST",
"WD_USER_NAME": "TEST",
"TCI_LOTNO": "20190522",
"SHOP_ORDER": "",
"SHOP_ORDER_ITEM": "",
"SHOP_ORDER_DESC": "",
"SPLIT_SFC_COUNT": "",
"SUP_LOTNO": "",
"REPRINT": null,
"PACKCOUNT": "",
"SFC": "",
"WEIGHT": "",
"PCS": "",
"SKIN_WEIGHT": -500
}
]
}
};
$.ajax({
type: "POST",
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
dataType: 'html',
success: function (ret) {
labeldata = ret;
window.alert("OK");
},
error: function (ret) {
window.alert(ret);
}
})
in controller side you can pass model like below.
public class PRINTDATA
{
public string storage { get; set; }
public string SPEC { get; set; }
public string ITEM { get; set; }
public string QTY { get; set; }
public string DEMAND { get; set; }
public string EXP_DATE1 { get; set; }
public string EXP_DATE2 { get; set; }
public string ALLERGENS { get; set; }
public string WD_DATE { get; set; }
public string WD_USER { get; set; }
public string WD_USER_NAME { get; set; }
public string TCI_LOTNO { get; set; }
public string SHOP_ORDER { get; set; }
public string SHOP_ORDER_ITEM { get; set; }
public string SHOP_ORDER_DESC { get; set; }
public string SPLIT_SFC_COUNT { get; set; }
public string SUP_LOTNO { get; set; }
public object REPRINT { get; set; }
public string PACKCOUNT { get; set; }
public string SFC { get; set; }
public string WEIGHT { get; set; }
public string PCS { get; set; }
public int SKIN_WEIGHT { get; set; }
}
public class PRINTREQUEST
{
public string PRINT_NAME { get; set; }
public int LABEL_QTY { get; set; }
public string TEMPLATE_PATH { get; set; }
public List<PRINTDATA> PRINT_DATA { get; set; }
}
public class Model
{
public PRINTREQUEST PRINT_REQUEST { get; set; }
}

kendo ui core entity framework core undefined in kendoMultiSelect

UI looks like this
<div class="col-md-3">
<select id="kMultiSelect" data-placeholder="Select Traits..." />
</div>
Javascript
<script>
var dataSourceTraits = new kendo.data.DataSource({
transport: {
read: {
url: "api/Traits",
dataType: "json"
},
create: {
url: "api/Traits",
type: "POST",
dataType: "json",
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
},
schema: {
model: {
ID: "Trait",
fields: {
ID: { type: "number" },
UID: { type: "string" }
}
}
}
});
$("#kMultiSelect").kendoMultiSelect({
autoBind: true,
dataTextField: "UID",
dataValueField: "ID",
dataSource: dataSourceTraits
});
</script>
Model
public int ID { get; set; }
public virtual string UID { get; set; }
.....
Controller
// GET: api/Traits
[HttpGet]
public IEnumerable<Trait> GetTrait()
{
// var test = _context.Trait;
return _context.Trait;
}
I have 4 rows in my table and I get 4 rows in the kendoMultiSelect each row just has "undefined" for text.
Looks like this
thanks for the help
after more help, entity framework core, by default, returns json. this datasource works
var dataSourceTraits = new kendo.data.DataSource({
type: "json",
transport: {
read: {
url: "api/Traits"
}
},
schema: {
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
}
});

How to pass updated data from grid to controller

In my kendo grid the update button does not work after I edit through pop up editor ,"result" is a Ajax call response, since I do not use services I don't need the "read" part that's why I commented it,
DataSource Initialization:
dataSource = new kendo.data.DataSource({
transport: {
//read: {
// url: result,
// dataType: "json"
//},
update: {
url: "/AdminTool/update_grid",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "DeviceIP",
fields: {
DeviceIP: { editable: false, nullable: true },
Producer: { type: "string" },
Model: { type: "string" },
DeviceType: { type: "string" },
Description: { type: "string" },
Username: { type: "string" },
Password: { type: "string" },
PublicIP: { type: "string" },
}
}
}
});
Kendo Grid Initialization:
$("#turbingrid").kendoGrid({
dataSource: result,
scrollable: false,
columns: [
{ field: 'DeviceIP', title: 'DeviceIP', width: '100px', id: 'DeviceIP' },
{ field: 'Producer', title: 'Producer', width: '80px', editor: ProductNameDropDownEditor, },
{ field: 'Model', title: 'Model', width: '120px' },
{ field: 'DeviceType', title: 'DeviceType', width: '100px', editor:deviceTypesList },
{ field: 'Description', title: 'Description', width: '100px' },
{ field: 'Username', title: 'Username',width:'120px' },
{ field: 'Password', title: 'Password', width: '100px' },
{ field: 'PublicIP', title: 'PublicIP', width: '120px' },
{ command: ["edit"], title: " ", width: "100px" }],
editable: "popup",
edit: function() {
document.getElementsByName("DeviceIP")[0].disabled = true;
},
editable: "popup"
});
Column Editors:
function ProductNameDropDownEditor(container, options) {
$('<input name="Producer" data-type="string"\">')
.appendTo(container)
.kendoDropDownList({
valuePrimitive: true,
dataSource: mydata,
dataTextField: "Text",
dataValueField: "Text",
});
}
function deviceTypesList(container, options) {
$('<input name="DeviceType" data-type="string" \">')
.appendTo(container)
.kendoDropDownList({
dataSource: mydata_deviceType,
dataTextField: "Text",
dataValueField: "Text",
//dataValueField: "ProductName",
});
}
My Controller:
[HttpPost]
public ActionResult update_grid(TurbineDvce frm)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
The Model I want to pass
public class TurbineDvce
{
public string TurbineId { get; set; }
public string DeviceIP { get; set; }
public string Producer { get; set; }
public string Model { get; set; }
public string DeviceType { get; set; }
public string Comments { get; set; }
public string Description { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string PublicIP { get; set; }
}
Use the parameterMap function to specify what data you wish to send to the controller function when editing each individual Kendo Grid row.
You can also specify within the function different methods of returning data based on the operation type.
In your case, an example would be like:
transport: {
update: {
url:"/AdminTool/update_grid",
dataType: "json"
},
parameterMap: function (data, operation) {
if(operation !== "read" && data) {
return kendo.stringify(data);
}
}
}
your controller action method is expecting parameter name "frm". So it will be like
parameterMap: function(options, operations){
if(operation !== "read" && options{
return {frm: options}
}
}

Populating EXT JS Store in a EXT form Panel

Using ASP.NET MVC action method to return Json to a view in order to display the data in a EXT JS form. I am always getting the "record" value as null in the function everythingLoaded even though i can see the action method is returning the JSON data after the Ext.Create. What i am trying to achieve is populate the firstName and lastName param's passed back from the action method to the textbox inside the panel. Can you help? Below is the code
->App.JS
Ext.onReady(function() {
//Define Store
Ext.define('StudentModel', {
extend: 'Ext.data.Model',
idProperty: 'Id',
fields: [
{ name: 'Id', type: 'int' },
{ name: 'firstName', type: 'string' },
{ name: 'lastName', type: 'string' },
{ name: 'birthDate', type: 'date' },
{ name: 'street', type: 'string' },
{ name: 'apartment', type: 'string' },
{ name: 'city', type: 'string' },
{ name: 'state', type: 'string' },
],
validations: [{
type: 'presence',
field: 'firstName'
}]
});
var store = Ext.create('Ext.data.Store', {
model: 'StudentModel',
storeId: 'StudentStoreId',
proxy: {
type: 'ajax',
url: '/Home/GetStudentSubmissions',
reader: {
type: 'json',
rootProperty: 'data'
}
},
autoLoad: { callback: everythingLoaded }
}
);
function everythingLoaded()
{
var record = store.getAt(0);
//Here record is always null
Ext.form('MyPanel').getForm().loadRecord(record);
}
Ext.define('StudentView', {
extend: 'Ext.form.Panel',
id: 'MyPanel',
alias: 'widget.StudentView',
title: 'Student Information',
resizable: false,
collapsible: true,
store:store,
bodyPadding: '5',
buttonAlign: 'center',
border: false,
trackResetOnLoad: true,
layout: {
type: 'vbox'
},
defaults: {
xtype: 'textfield',
msgTarget: 'side',
labelAlign: 'top',
labelStyle: 'font-weight:bold'
},
items: [{
xtype: 'fieldcontainer',
layout: 'hbox',
defaultType: 'textfield',
width: '100%',
fieldDefaults: {
labelAlign: 'top',
labelStyle: 'font-weight:bold'
},
items: [{
fieldLabel: 'First Name',
name: 'firstName',
allowBlank: false
}, {
fieldLabel: 'Last Name',
name: 'lastName',
allowBlank: false
}]
}]
});
//Here count is always 0
var i = store.getCount();
Ext.create('widget.StudentView', {
renderTo: 'studentMasterForm'
});
});
-> C# Action Method
public JsonResult GetStudentSubmissions()
{
return Json(GetStudents(), JsonRequestBehavior.AllowGet);
}
public Student GetStudents()
{
Student studobj = new Student();
studobj.Id = 1;
studobj.firstName = "Aravind";
studobj.lastName = "R";
studobj.state = "NJ";
studobj.street = "Center Grove";
studobj.birthDate = new DateTime(1989, 6, 6);
studobj.apartment = "DD8";
studobj.city = "XYZ";
return studobj;
}
}
->Student Model Class
public class Student
{
public int Id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public DateTime birthDate { get; set; }
public string street { get; set; }
public string apartment { get; set; }
public string city { get; set; }
public string state { get; set; }
}
Your c# code returns one object "Student", but it is supposed to return an object which have an array of students as its "data" property.
You need to return an object of this type:
public class ExtStore
{
public List<Student> data = new List<Student>();
}
this way for example:
public ExtStore GetStudents()
{
Student studobj = new Student();
studobj.Id = 1;
studobj.firstName = "Aravind";
studobj.lastName = "R";
studobj.state = "NJ";
studobj.street = "Center Grove";
studobj.birthDate = new DateTime(1989, 6, 6);
studobj.apartment = "DD8";
studobj.city = "XYZ";
ExtStore exs = new ExtStore();
exs.data.Add(studobj);
return exs;
}

Posting javascript array of objects to MVC4 controller

This is my controller action:
public ActionResult BrowsePartial(IList<SearchParam> searchParams = null)
{
//...
}
This is the object model:
public class SearchParam
{
public string Order { get; set; }
public string Type { get; set; }
public string Value { get; set; }
}
And here is how i send data to controller:
$.ajax(
{
type: "GET",
url: url,
data: { searchParams: [{ Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }] },
mode: "replace",
cache: false,
});
Now, when i debug the action, i have an IList<SearchParam> that is correctly initialized with 3 elements. However, fields of each SearchParam object (Order, Type and Value) are initialized to null. What could be the problem here?
I think, the only way you can send your array parameter in a single request is to stringify it, and deserialize in your controller.
$.ajax(
{
type: "GET",
url: url,
data: { searchParams: JSON.stringify([{ Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }, { Order: "fghfdhgfdgfd", Type: "sasdsa", Value: "saddsadsads" }])},
mode: "replace",
cache: false,
});
public ActionResult BrowsePartial(string searchParams = null)
{
SearchParam params = JsonConvert.DeserializeObject<SearchParam>(searchParams);
}
But I maybe mistaken ;)

Categories