The string can not be recognized as a valid DateTime value - javascript

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

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; }
}

How to work with enum in kendo grid

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.

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