Submit multiple tabs within one view ASP.NET MVC - asp.net-mvc

I have an ASP .NET application with multiple tabs on a view, each tab containing several inputs for each course attendee (name, phone number, job title, etc).
I created a jquery function to collect data from views and generate the JSON accordingly:
function getAttendees() {
var sections = [];
$(".divWithInputs").each(function (i, val) {
var tab = $(val).serializeArray();
sections.push(tab);
});
return sections;
}
And the submit function:
$("#checkoutAttendees").click(function () {
var formData = new FormData();
formData.append("Attendees", JSON.stringify(getAttendees()));
$.ajax({
url: "/controllerURL",
type: 'POST',
contentType: "application/json; charset=utf-8",
cache: false,
contentType: false,
processData: false,
data: formData,
success: function (response) {
alert(response);
}
});
});
I have an issue when reading the JSON, because I need an IEnumerable of Attendee objects to populate with this sort of data:
[
[
{
"name":"first-name-attendee-0",
"value":"Jon"
},
{
"name":"last-name-attendee-0",
"value":"Stark"
},
{
"name":"email-attendee-0",
"value":"jon.stark#northwall.com"
},
{
"name":"phone-attendee-0",
"value":"0181042981029840"
},
{
"name":"company-attendee-0",
"value":"Nightwatch"
},
{
"name":"job-title-attendee-0",
"value":"King"
}
],
[
{
"name":"first-name-attendee-1",
"value":"Aria"
},
{
"name":"last-name-attendee-1",
"value":"Stark"
},
{
"name":"email-attendee-1",
"value":"noemail#nodomain.com"
},
{
"name":"phone-attendee-1",
"value":"000000000000000"
},
{
"name":"company-attendee-1",
"value":"No organization"
},
{
"name":"job-title-attendee-1",
"value":"Killer"
}
],
[
{
"name":"first-name-attendee-2",
"value":"Mad"
},
{
"name":"last-name-attendee-2",
"value":"King"
},
{
"name":"email-attendee-2",
"value":"mad.king#yahoo.com"
},
{
"name":"phone-attendee-2",
"value":"019209840921840219"
},
{
"name":"company-attendee-2",
"value":"Kingdom"
},
{
"name":"job-title-attendee-2",
"value":"King"
}
]
]
Any advise on how to properly transform data from JSON into a list of Attendees ?
Thank you.

Solution: in backend I had to create a list of lists of NameValuePair
The Action method looks like this:
[HttpPost]
public ActionResult TrainingBook(FormCollection formCollection)
var viewModel = new TrainingFormViewModel();
var attendeesListJSON = formCollection["Attendees"];
var attendeesJson = JsonConvert.DeserializeObject<List<List<KeyValuePair<string, string>>>>(attendeesListJSON);
List<Attendees> attendees = new List<Attendees>();
foreach (var item in attendeesJson)
{
attendees.Add(new Attendees {
FirstName = item[0].Value,
LastName = item[1].Value,
WorkEmailAddress = item[2].Value,
PhoneNumber = item[3].Value,
Organization = item[4].Value,
JobTitle = item[5].Value
});
}
A key value pair is name and value for an input, the first list of key value pairs is one attendee, the the list of lists, ofc, all the attendees.

Related

How can I get the selected checkbox in kendo grid?

I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "Descripción" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.

My Kendo grid is not populating with JSON object returned from Controller

I am writing an MVC application that is storing certain information in session variables. I am able to populate a list I have in my repo class without a problem. The issue I am having is when I click on my search Client controller it just gives me a JSON object but does not populate my Kendo Grid.
This is my datasource:
var clientSearch = new kendo.data.DataSource({
transport: {
read: {
url: "SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
create: {
url: "ClientInformation",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST"
},
parameterMap: function (data, operator) {
if (operator != "read")
return JSON.stringify(viewModel);
}
},
schema: {
model: {
id: "clientName",
}
}
});
This is my Grid:
$("#grid").kendoGrid({
dataSource: clientSearch,
columns: [{
field: "clientName",
title: "Client Name",
},
{
field: "clientNumber",
title: "Client Number",
},
{
field: "clientType",
title: "Client Type",
}]
})
This is my controller that is returning my JSON object:
[HttpGet]
public ActionResult SearchClient()
{
HttpSessionStateBase session = HttpContext.Session;
Repo repo = new Repo(session);
var result = repo.GetClient();
return Json(new
{
list = result,
count = result.Count
}, JsonRequestBehavior.AllowGet);
}
You need to specify your fields in the schema of data source object:
var clientSearch = new kendo.data.DataSource({
transport: {
read: {
url: "SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json"
},
create: {
url: "ClientInformation",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST"
},
parameterMap: function (data, operator) {
if (operator != "read")
return JSON.stringify(viewModel);
}
},
schema: {
model: {
id: "clientName",
fields: {
ID: { editable: false },
clientName: { editable: false },
clientNumber: { editable: false },
clientType: { editable: false }
}
}
});
Kendo.Mvc expects DataSourceRequest and DataSourceResult when binding grid as such:
public ActionResult SearchClient([DataSourceRequest] DataSourceRequest request)
{
HttpSessionStateBase session = HttpContext.Session;
Repo repo = new Repo(session);
var result = repo.GetClient();
return Json(new
{
list = result.ToList().ToDataSourceResult(request, ModelState)
}, "application/json", JsonRequestBehavior.AllowGet);
}

Update Kendo Grid based On Search Form Post

I've been doing alot of searching but haven't found a clear answer for this. I have a set up textboxes that and a submit button and a Kendo UI grid. I want to post the data to the grid's datasource so that it will return the results based on the criteria. I am not using the MVC wrappers.
EDIT:
I've gotten closer but I can't seem to get the datasource to send the post data when I click submit. I've debugged and in my $("#fmSearch").submit it is hitting the jquery plugin and I've confirmed that it is converting the form data to JSON properly, but it seems as though it it not sending the updated information to the server so that the Action can read it.
Javascript
var dsGalleryItem = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Content("~/Intranet/GalleryItem/SearchGalleryItems")',
type: "POST",
data: $("#fmSearch").serializeFormToJSON(),
cache: false
}
},
schema: {
model: {
id: "galleryItemID",
fields: {
galleryItemID: {
nullable: true
},
imageName: {},
collectionName: {},
categoryName: {},
lastUpdatedOn: { type: "date" }
}
}
}
});
var gvResults = $("#gvResults").kendoGrid({
autoBind:false,
columns: [{
field: "imageName",
title: "Item Name",
template: "<a href='#Url.Content("~/Intranet/GalleryItem/Details/")#=galleryItemID#'> #=imageName#</a>"
}, {
field: "collectionName",
title: "Collection"
}, {
field: "categoryName",
title: "Category"
}, {
field: "lastUpdatedOn",
title: "Last Updated",
format: "{0:M/d/yyyy}"
}
],
selectable: "row",
change: onRowSelect,
dataSource: dsGalleryItem
});
$("#fmSearch").submit(
function (event) {
event.preventDefault();
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
});
MVC Action
[HttpPost]
public JsonResult SearchGalleryItems(string keyword, int? category, int? collection, DateTime? startDate, DateTime? endDate)
{
var galleryItemList = (from g in db.GalleryItems
//where g.imageName.Contains(keyword)
select new GalleryItemViewModel
{
galleryItemID = g.galleryItemID,
imageName = g.imageName,
collectionName = g.collection.collectionName,
categoryName = g.category.categoryName,
lastUpdatedOn = g.lastUpdatedOn
});
var galleryItemCount = Json(galleryItemList.ToList());
return Json(galleryItemList.ToList()); ;
}
The action is not setup to retrieve different data right now I just need to know how to connect the form to the grid.
Found the problem. I had this:
dsGalleryItem.read({ data: $("#fmSearch").serializeFormToJSON() });
It needed to be this:
dsGalleryItem.read($("#fmSearch").serializeFormToJSON());

How to initialize the selection for rails-select2 in BackboneForms schema?

The project uses marionette-rails, backbone-on-rails, select2-rails and this port to BackboneForms to provide a multiselect form field. The select options are available to the user. They are retrieved from the collection containing the total list of options:
MyApp.module("Products", function(Products, App, Backbone, Marionette, $, _) {
Products.CustomFormView = Products.CustomView.extend({
initialize: function(options) {
this.model.set("type", "Product");
Products.EntryView.prototype.initialize.apply(this, arguments);
},
schemata: function() {
var products = this.collection.byType("Product");
var productTypes = products.map(function(product){
return {
val: product.id,
label: product.get("name")
};
});
return {
productBasics: {
name: {
type: "Text",
title: "Name",
editorAttrs: {
maxLength: 60,
}
},
type: {
type: 'Select2',
title: "Product type",
options: {
values: productTypes,
value: [3, 5],
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
},
editorAttrs: {
'multiple': 'multiple'
}
}
}
};
}
});
});
Do I initialize the value correctly in options.value? How comes initSelection is never called? I copied the function from the documentation - it might be incomplete for my case. None of the products with the IDs 3 and 5 is displayed as the selection.
initSelection is only used when data is loaded asynchronously. My understanding is that there is no way of specifying the selection upon initialization if you are using an array as the data source for a Select2 control.
The best way of initializing the selection is by using setValue after the form is created. Here is a simplified example based on the code in your example.
var ProductForm = Backbone.Form.extend({
schema: {
type: {
type: 'Select2',
title: "Product type",
options: {
values: productTypes,
},
editorAttrs: {
'multiple': 'multiple'
}
}
});
var form = new ProductForm({
model: new Product()
}).render();
form.setValue("type", [3, 5]);
You can use value function (http://ivaynberg.github.io/select2/#documentation) in setValue. I personally recomend you to use this backbonme-forms plugin: https://gist.github.com/powmedia/5161061
There is a thread about custom editors: https://github.com/powmedia/backbone-forms/issues/144

Kendo UI Grid not showing JSON data

I am facing this problem for quite a while now with the problem that I am unable to bind JSON data that my controller action is passing to the kendo UI Grid, there were few JavaScript issues before but now they are gone but still my grid is not showing any results:
In Model:
public object GetResult(string id)
{
var sqlCom = new SqlCommand("SELECT [No],[Desc],[Date],[Height],[Final] FROM [cr_form] WHERE [uId]=#id;", sqlConn);
sqlCom.Parameters.AddWithValue("#id", id);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
var rcrds = GETSQLRESULTS(sqlCom);
try
{
int i = 0;
if (rcrds != null || rcrds.HasRows)
{
//jsonWriter.WriteStartObject();
while (rcrds.Read())
{
jsonWriter.WriteStartObject(); //Changed
for (int j = 0; j < rcrds.FieldCount; j++)
{
jsonWriter.WritePropertyName(rcrds.GetName(j)); // column name
jsonWriter.WriteValue(rcrds.GetValue(j)); // value in column
}
i++;
jsonWriter.WriteEndObject(); //Changed
}
//jsonWriter.WriteEndObject();
}
}
catch (Exception ex) { }
return jsonWriter;
}
In Controller:
public ActionResult GetRecords()
{
var usrObj = new User();
var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
//Till here jsnRslt contains this string: “{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null,"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"askjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfklaskjfkajsfkl","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"safasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0,"No":null,"Desc":"asfasfasf","Date":"2013-03-27T00:00:00","Height":2,"Final":0}”
//After Changes in the Model I am getting it in the required Array format:
//{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null}
//{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0}
//{"No":null,"Des...
return Json(jsnRslt, JsonRequestBehavior.AllowGet);
}
In View:
<div>
<script type="text/javascript">
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "json",
serverPaging: true,
pageSize: 5,
groupable: true,
selectable: "row",
transport: { read: { url: "Records", dataType: "json"} }
},
height: 400,
scrollable: true,
sortable: true,
filterable: true,
pageable: true,
columns: [
{ field: "No", title: " No" },
{ field: "Desc", title: "Description" },
{ field: "Date", title: "Date" },
{ field: "Height", title: "Height" },
{ field: "Final", title: "Final" }
],
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
}
});
});
</script>
</div>
But after all this all I can see is an empty grid. And no errors in JavaScript console.
Please help
The JSON that you return from the server should be array. You currently it seems that you are returning single objects with multiple fields that are the same.
Here is an example how the JSON should look like:
[{"No":null,"Desc":"asfasfasfasfasfasfasfasfasfasfasfasf","Date":"2013-03-27T00:00:00","Height":0,"Final":null},
{"No":null,"Desc":"etwetwetwetwet","Date":"2013-03-27T00:00:00","Height":0,"Final":0},
{"No":null,"Desc":"asfasfasfskfjklajsfkjasklfjklasjfklajsfkljaklsfjklasjfkljasfkljlasf","Date":"2013-03-27T00:00:00","Height":0,"Final":0}]
I think following code will be useful for you and let me know if you have any problem:
$('#gridName').kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
contentType: "application/json; charset=utf-8",
type: "POST",
url: 'YourURL'
}
},
pageSize: 10,
type: "json"
},
scrollable: true,
sortable: true,
resizable: true
});
Inside you dataSource set data.
data: #Html.Raw(Json.Encode(Model.RemoteObject)),
RemoteObject is you object containing all data.
First I check your tranport read URL. have you trace the controller if it fires the GetRecords command?
transport:
{
read: {
//if you don't use area then remove it
url: "#Url.Action("GetRecords", new { area = "YourAreaName", controller = "YourControllerName" })",
dataType: "json"
}
}
if it still doesn't fix your problem, then modify your Controller,
public ActionResult GetRecords([DataSourceRequest] DataSourceRequest request)
{
var usrObj = new User();
var jsnRslt = usrObj.GetResult(Session["Id"].ToString());
return Json(jsnRslt.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
here's the link to understand the Kendo's ToDataSourceResult

Resources