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; }
}
Related
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.
I'm trying to Create/Update data in Kendo UI Grid using Web Api connected to a SQL database.
Here is my Usuarios Class
public class UsuariosModel
{
[Key]
public int Codigo { get; set; }
public String Usuario_Nombre { get; set; }
public String Password { get; set; }
public String Nombre { get; set; }
public String Apellido { get; set; }
public DateTime Fecha_Creacion { get; set; }
public String Telefono { get; set; }
public String Email { get; set; }
}
Create Usuarios
public void Guardar(String Nombre, String Apellido, String Usuario_Nombre, String Password, DateTime Fecha_Creacion, String Telefono, String Email)
{
try
{
DataBaseManager cn = new DataBaseManager();
cn.Ejecutar("INSERT INTO USUARIOS(USU_NOMBRE, USU_APELLIDO, USU_NOMBRE_USUARIO, USU_PASSWORD, USU_FECHA_CREACION, USU_TELEFONO, USU_EMAIL) VALUES('" + Nombre + "','" + Apellido + "','" + Usuario_Nombre + "','" + Password + "','" + Fecha_Creacion + "','" + Telefono + "','" + Email + "')");
}
catch (Exception ex)
{
throw ex;
}
}
Controller
[HttpPost]
public void Guardar([FromBody] JObject data)
{
String Nombre = data["Nombre"].ToString();
String Apellido = data["Apellido"].ToString();
String Usuario_Nombre = data["Usuario_Nombre"].ToString();
String Password = data["Password"].ToString();
DateTime Fecha_Creacion = Convert.ToDateTime(data["Fecha_Creacion"].ToString());
String Telefono = data["Telefono"].ToString();
String Email = data["Email"].ToString();
new UsuariosModel().Guardar(Nombre, Apellido, Usuario_Nombre, Password, Fecha_Creacion, Telefono, Email);
}
And Grid schema in JavaScript
model: {
id: 'Codigo',
fields: {
Codigo: { nullable: false, editable: false, format: '{0:n0}', type: 'number' },
Nombre: { nullable: false, editable: true, type: 'string' },
Apellido: { nullable: false, editable: true, type: 'string' },
Usuario_Nombre: { nullable: false, editable: true, type: 'string' },
Password: { nullable: false, editable: true, type: 'password' },
Fecha_Creacion: { nullable: false, editable: true, type: 'date'},
Telefono: { nullable: false, editable: true, type: 'string'},
Email: { nullable: false, editable: true, type: 'email' }
}
}
But when I create or update Usuarios, this exception happens:
DateTime Fecha_Creacion = Convert.ToDateTime(data["Fecha_Creacion"].ToString());
The string can not be recognized as a valid DateTime value
Columns
{
field: 'Fecha_Creacion',
title: 'Fecha de Creacion',
width: 150,
format: '{0:dd/MM/yyyy}'
//template: '#= kendo.toString(kendo.parseDate(DateOfBirth, "yyyy-MM-dd"), "MM/dd/yyyy") #'
THANKS,
Sorry for my English
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}
}
}
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 ;)
I try to send an array of json objects to server:
var objectData = [
{ Description: "Bezeichnung", Value: "1", Name: "Betrag (Brutto)" },
{ Description: "Dies ist die erste Bezeicnung", Value: "101", Name: "11,90" },
{ Description: "Dies ist die zweite Bezeicnung", Value: "12", Name: "11,90" }
];
$.ajax({
url: "/system/createinvoice",
data: JSON.stringify({ pos: objectData }) ,
dataType: 'json',
type: 'POST',
});
C#
public class InvoicePos
{
public string Description { get; set; }
public Nullable<double> Value { get; set; }
public string Name { get; set; }
}
[POST("/system/createinvoice")]
public void newquestion2(InvoicePos[] pos)
{
// pos is always null
}
The dataType property is saying what you expect back from the server. Try setting the contentType:
contentType: 'application/json'
Try
data: JSON.stringify({ pos: #objectData })
Also, check what is being rendered in the View through the browser. The reason you are getting null is likely because JavaScript is not getting a proper value.
function SendArrayOfObjects()
{
var things = [{ id: 1, color: 'red' }, { id: 2, color: 'blue' }, { id: 3, color: 'yellow' }];
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/MyServices.aspx/GetData")%>",
data: JSON.stringify({ objdata: things }),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function()
{
$("#msg").html("data sent successfully!");
},
error: function()
{
$("#msg").html(" Can not send data!");
}
});
}