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 ;)
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.
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" }
}
}
}
});
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}
}
}
I am trying to create dynamic listbox values but getting this error in console:
Uncaught TypeError: Cannot assign to read only property 'active' of [
Here's my code( pasting only the code for listbox ):
body: [
{
type: 'listbox',
name: 'type',
label: 'Panel Type',
value: type,
'values': get_author_list(),
tooltip: 'Select the type of panel you want'
},
]
.....
And I am calling this function to get dynamic list...
function get_author_list() {
var d = "[{text: 'Default', value: 'default'}]";
return d;
}
I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax?
Thanks, in advance!!
I needed something similar for .NET site. Even though is not great code I hope it can help someone.
tinymce.PluginManager.add('DocumentSelector', function (editor, url) {
// Add a button that opens a window
editor.addButton('DocumentSelector', {
text: 'Document',
icon: false,
title: "Document Selector",
onclick: function () {
var _documentList;
//load all documents
var _data = JSON.stringify({/* Some data */});
$.ajax({
type: "POST",
url: "/api/TinyMCE/GetDocuments",
data: _data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
_documentList = eval('(' + data + ')');
// Open window
editor.windowManager.open({
title: 'Document Selector',
body: [
{
type: 'listbox',
name: 'DocURL',
label: 'Documents',
values: _documentList
},
{
type: 'textbox'
, name: 'TextToDisplay'
, value: _text
, label: 'Text To Display'
},
{
type: 'textbox'
, name: 'TitleToDisplay'
, value: _title
, label: 'Title'
},
{
type: 'listbox',
name: 'TheTarget',
label: 'Target',
values: [{ text: 'None', value: "_self" }, { text: 'New Window', value: "_blank" }],
value: _target
}
],
onsubmit: function (e) {
// Insert content when the window form is submitted
}
});
},
error: function (xhr, status, error) {
alert("Error! " + xhr.status + "\n" + error);
}
});
}
});
});
And here it is some of the Behind code
public class TinyMCEController : ApiController
{
public class DocumentsInfo
{
// Some data
}
public class DocumentList
{
public string text { get; set; }
public string value { get; set; }
}
[HttpPost]
[ActionName("GetDocuments")]
public object GetDocuments(DocumentsInfo docInfo)
{
//Test data
List<DocumentList> _DocumentList = new List<DocumentList>();
_DocumentList.Add(new DocumentList {
text = "Document1.pdf",
value = "value1"
});
_DocumentList.Add(new DocumentList
{
text = "Document2.pdf",
value = "value2"
});
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(_DocumentList);
return json;
}
}
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!");
}
});
}