Send the content-type to webapi from kenod dropdown list - c#

I need to send the contentType as "application/json" to webApi controller. below is the code which i used and it is not working.
#(Html.Kendo().DropDownList()
.Name("ddlPatientClass").AutoBind(true)
.HtmlAttributes(new { style = "width: 67px!important;" })
.DataTextField("ModuleName")
.DataValueField("RoleId")
.ContentType("application/json")
.DataSource(source =>
{
source.Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "MedicalVisit", Action = "GetPatientClass" })).Type(HttpVerbs.Get));//.Type(HttpVerbs.Get).Data("ModuleParamCP"));
})
)

Instead of #Htmlhelper class, you can use below Kendo UI JQyery dropdown to bind JSON data as below.
HTML
<input id="ddlPatientClass" name="ddlPatientClass" class="custom-select" style="width: 100%;" />
JQuery
$(document).ready(function () {
var data = [
{ text: "0", value: "0" },
{ text: "10", value: "10" },
{ text: "25", value: "25" },
{ text: "30", value: "30" },
{ text: "100", value: "100" }
];
// This data you can get from WebApi - using Ajax call
// After get JSON data from webApi - you can create DropDownList as below
$("#ddlPatientClass").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data,
index: 0,
optionLabel: "-- Choose % --",
});
});

Related

ASP.NET Core MVC : #Html.DropDownList on change pass ViewBag as parameter

I am creating an ASP.NET Core MVC application. I have a #Html.DropDownList and in the on change function, I want to pass as parameter a ViewBag value
#Html.DropDownList("PageSize", new SelectList(new Dictionary<string, int> { { "10", 10 }, { "20", 20 }, { "30", 30 }, { "40", 40 }, { "50", 50 }, { "100", 100 } }, "Key", "Value", Convert.ToString(ViewBag.PageSize)), new { id = "SearchPageSize", style = "width: 100px;", #onchange = "AAA(ViewBag.CurrentSort)" })
The function AAA is never called, and I get this error
Uncaught ReferenceError: ViewBag is not defined at HTMLSelectElement.onchange
It does not like how I am passing the parameter ViewBag.CurrentSort
How can I solve this?
Thanks
The issue is the context, which is c#.
Since the property being set is from the c# side, no # is required.
To get the quotes around the parameter, use string.Format.
onchange=string.Format("AAA('{0}')", ViewBag.CurrentSort)

Passing drop down value attribute to the database:angularjs

I am using crystal reports to print data in the database. I want to pass the value of the drop down as a parameter to the database. but my code gives an error saying Input string was not in a correct format. Below is a sample of my code.
This is my html code.
<div class="col-sm-7">
<select kendo-drop-down-list
name="PaymentCategory"
class="k-fill"
ng-init="Init()"
ng-model="ReceiptCancelWF.PaymentCategory"
k-placeholder="'Select Payment Category'"
k-data-text-field="'text'"
k-data-text-field="'Value'"
k-data-value-field="'Key'"
k-data-source="PaymentCategoryDropdown"
ng-disabled="ReceiptCancelWF.AllPayCat"></select>
</div>
This is my front end code.
$scope.PaymentCategoryDropdown = [
{ "text": "Select", "value": 0 },
{ "text": "AR", "value": 1 },
{ "text": "CB", "value": 4 },
];
$scope.PrintEntry = function (form) {
var PaymentCategory = $scope.ReceiptCancelWF.PaymentCategory;
PrintService.OpenPrint('POST', appConfig.REPORT_URL + 'CPOSReportViewer.aspx', { type: "ReceiptCancellationWF", PaymentCategory: PaymentCategory},'_blank'
};
This is my back end code.
myReport.Load(Server.MapPath("~/CPOSReport/MIS/CancellationReports/ReceiptCancellationWorkFlow.rpt"));
myReport.SetParameterValue("#EntryType", Convert.ToInt32(Request.Form["PaymentCategory"]));
I want to pass the value attribute as a integer to the database.
I figured it out. I change my html code and frond end code as below.
<div class="col-sm-7">
<select kendo-drop-down-list
name="PaymentCategory"
class="k-fill"
ng-init="Init()"
ng-model="ReceiptCancelWF.PaymentCategory"
k-placeholder="'Select Payment Category'"
k-data-text-field="'text'"
k-data-value-field="'value'"
k-data-source="PaymentCategoryDropdown"
ng-disabled="ReceiptCancelWF.AllPayCat"></select>
$scope.PaymentCategoryDropdown = [
{ "text": "Select", "value": "0" },
{ "text": "AR", "value": "1" },
{ "text": "CB", "value": "4" },
];

How to add row number to kendo ui grid?

I have a kendo ui grid in my page that has some columns.
Now I want to add a column to it that shows me row number.
How to I do this?
Thanks.
Initialize a variable and show it in column as template: "#= ++record #"
Working Demo
Here is code:
var record = 0;
$("#grid").kendoGrid({
dataSource: {
data: [{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" },{ foo: "foo" }, { foo: "foo" }, { foo : "foo1" }],
pageSize: 10
},
sortable: true,
columns: [ {
title: " ",
template: "#= ++record #",
width: 30
}, { field: "foo" }],
pageable: true,
dataBinding: function() {
record = (this.dataSource.page() -1) * this.dataSource.pageSize();
}
});
For Razor you also need to actually show the number also: (not enough point thingies to comment)
above the grid:
#{int counter = 1;}
inside column definitions:
columns.Template(#<text>
<span>#counter #{ counter++; }</span>
</text>).Title("#");
there is no need to define any variables, you can get help from databound event:
$("#grid").kendoGrid({
sortable: true,
dataSource: [{
name: "Jane Doe",
age: 30
}, {
name: "John Doe",
age: 33
}],
columns: [{
field: "name"
}, {
field: "age"
}, {
field: "rowNumber",
title: "Row number",
template: "<span class='row-number'></span>"
}],
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1
+ ($("#grid").data("kendoGrid").dataSource.pageSize() * ($("#grid").data("kendoGrid").dataSource.page() - 1));;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
}
});
YD1m's template did not work for me it treated the variable like a string. So I had to implement it like so:
columns.Template(#<text>#((long)counter++)</text>)
For asp.net mvc wrapper you should use something like this:
#{
var counter = 1;
}
#( Html.Kendo().Grid<Types>()
.Name("grid")
.Columns(columns =>
{
// Define a template column with row counter
columns.Template(#<text>#counter++</text>);
// Define a columns from your data set and set a column setting
columns.Bound(type => type.id);
columns.Bound(type=> type.name).Title("Name");
// add more columns here
})
)
Based on Ehsan Mirsaeedi's great answer, I came up with this version, which assigns indices starting at 0 instead of row numbers starting at 1, skips group headers if the grid is grouped, and handles the case when the grid is not paged.
I needed these indices in order to add a template with a hidden input to each column, so that I can then submit the grid's values along with the entire form.
I think it's related enough and worth adding to the thread...
Code:
var theGrid = $("#grid").data("kendoGrid");
var rows = this.items().filter(function (index, item) {
return $(item).hasClass("k-grouping-row") == false;
});
$(rows).each(function () {
var index = $(this).index();
//prevent group header rows from incrementing index
if (theGrid.dataSource.options.group != null && theGrid.dataSource.options.group.length > 0)
index -= $(this).prevAll("#grid tr.k-grouping-row").length;
//adjust indices for current page
if (theGrid.options.pageable == true)
index += theGrid.dataSource.pageSize() * (theGrid.dataSource.page() - 1);
//add the value to the grid's data object
theGrid.dataItem(this).rowNumber = index;
//and update the grid's HTML
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
Result:
If you need, row number in editable grid
$(document).ready(function(){
$("#grid").kendoGrid({
dataSource: {
data: null,
schema: {
model: {
id: "register_No",
fields: {
register_No: {editable: true},
myEditableField: {editable: true},
}
}
}
},
edit:function(e){
var fields= $('input[name="register_No"]');
fields.attr('disabled', true);
fields.removeClass('k-input k-textbox');
fields.addClass('none');
//create this class and set border and background none
$('input[name="myEditableField"]').focus();
},
save:function(e){
var total=e.sender.dataSource.data().length;
if(e.model.register_No==""){
e.model.register_No=total;
}
},
remove:function(e){
var grid = $("#grid").data("kendoGrid");
var todos=grid.dataSource.data();
var id_actual=e.model.register_No;
var count=1;
for(var i=0;i<todos.length;i++){
if(todos[i].register_No!==id_actual){
var data = grid.dataSource.at(i);
data.set("register_No", count);
count++;
}
}
}
, height: 280,
toolbar: ["create"],
scrollable: true,
editable: {mode:"inline", createAt: "bottom", confirmation: true
}
,
columns: [
{field: "register_No",title: "No", width: 30},
{field: "myEditableField", title: "Any Field", width: 120},
{field: "options", command: ["edit", "destroy"], width: 200}
]
});
});
<div id="grid"></div>
Declare a variable for row counting:
var rowNumber = 0;
Use it in your template with ++ operator to increment it for each iteration:
#= ++rowNumber #
This also works for Kendo UI ListView.
See the official document:
http://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Templates/add-row-numbers

Using knockout to copy objects from one array to another

I'm using a Webforms page. On it I have a KnockoutJS ViewModel that gets a serialized JSON list of "Customers" by making a call to the backend C# code.
I data-bind that array to a combobox and I want to add the selected Customer to another array when a button is clicked. I want the list of selected customers to appear in a simple unordered list.
I'm not quite sure how add Customers to the "SelectedCustomers" property when clicking on the "Add" button. Note: I don't wan't move them, just copy.
Javascript/Knockout Bindings
<script type="text/javascript">
$(document).ready(function() {
function CustomerViewModel() {
var self = this;
self.Customers= <%= getJson() %>;
self.SelectedCustomers = ko.observableArray([]);
//operations
self.addCustomerToList = function() {
//Add selected customer to self.SelectedCustomers
}
}
ko.applyBindings(new CustomerViewModel());
});
</script>
HTML elements
<select data-bind="options: Customers, optionsText: 'CustomerName', value: CustomerID, optionsCaption: 'Select a Customer to Add'"></select>
<button type="submit">Add Customer</button>
Selected Customers:
<ul data-bind="foreach: SelectedCustomers">
<li><span data-bind="text: CustomerName"></span></li>
</ul>
You can databind the selected customer from the list to another array (ChosenCustomers).
See http://knockoutjs.com/documentation/selectedOptions-binding.html
<select data-bind="selectedOptions: ChosenCustomers, options: Customers, optionsText: 'CustomerName', value: CustomerID, optionsCaption: 'Select a Customer to Add'"></select>
In the javascript class the ChosenCustomers array is defined:
self.Customers= <%= getJson() %>;
self.SelectedCustomers = ko.observableArray([]);
self.ChosenCustomers = ko.observableArray([]);
In the method we check if it's not already there and if not add it to the SelectedCustomers array.
self.addCustomerToList = function() {
self.ChosenCustomers.each(function(index, item){
if(self.SelectedCustomers.indexOf(item) < 0){
self.SelectedCustomers.push(item);
}
});
};
Note: although your combobox may only allow for 1 customer to be selected at a time, the selectedOptions binding will always be an array, but will only have 1 item in it.
I was able to figure this out. Check out my solution here:
http://jsfiddle.net/6vBsm/1/
function ViewModel() {
var self = this;
self.Components = ko.observableArray([{
"ID": "1",
"Name": "Tennis Ball",
"Description": "Basic Yellow Tennis Ball 9",
"Quantity": 0,
"Price": 1.99,
"Discount": 0.0,
"FreePeriods": 0
}, {
"ID": "2",
"Name": "Hockey Stick",
"Description": " Premium Carbon Fiber Construction",
"Quantity": 0,
"Price": 67.99,
"Discount": 0.0,
"FreePeriods": 0
}, {
"ID": "3",
"Name": "Cycling Helmet",
"Description": " For going fast.",
"Quantity": 0,
"Price": 226.99,
"Discount": 0.0,
"FreePeriods": 0
}]);
self.componentToAdd = ko.observable();
self.SelectedComponents = ko.observableArray([]);
// Computed data
self.totalSurcharge = ko.computed(function () {
var total = 0;
for (var i = 0; i < self.SelectedComponents().length; i++)
total += self.SelectedComponents()[i].Price;
return total;
});
//Operations
self.addComponent = function () {
var mycopy = JSON.parse(ko.toJSON(self.componentToAdd()));
self.SelectedComponents.push(mycopy);
};
}
ko.applyBindings(new ViewModel());
Lets say you want to copy self.SelectedCustomers = ko.observableArray([]);
Then use slice function of knockout like below
self.newselectedCustomers(self.SelectedCustomers().slice(0));

Firebug errors that I cannot make them disappear

I keep getting this error in Firebug:
d is undefined
[Break On This Error] randId:function(d){return(d?d:b.jgrid....(i,d);if(g)return d;return d.length>
I use JqGrid Version: 4.3.1
My controller method looks like this :
public JsonResult CategoryList(int page)
{
List<CategoryDTO> categories = ServiceUtil.AuctionService.ListCategories();
List<dynamic> json = new List<dynamic>();
if (categories != null && categories.Count > 0)
{
foreach (CategoryDTO cat in categories)
{
json.Add(new { Id = cat.Id, Name = cat.Name, Update = cat.LastUpdate, Regex = cat.ValidationXSD });
}
}
var result = new
{
total = 1,
page = page,
records = categories == null ? 0 : categories.Count,
rows = (from cat in categories.Take(10)
select
new { Id = cat.Id, Name = cat.Name, Update = cat.LastUpdate, Regex = cat.ValidationXSD }
).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
}
The view like this :
$(document).ready(function () {
$("#jqgridListCategory").jqGrid({
url: '/Admin/ManageCategory/CategoryList',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'Name', 'LastUpdate', 'RegularExpression'],
colModel: [{ name: 'Id', index: 'Id', width: 40, align: 'left' }, { name: 'Name', index: 'Name', width: 400, align: 'left' }, { name: 'LastUpdate', index: 'LastUpdate', width: 40, align: 'left' }, { name: 'RegularExpression', index: 'RegularExpression', width: 40, align: 'left'}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
caption: 'Categories'
});
});
I cannot figure out what is wrong, any ideas?
Edit 1: Use latest jquery version 1.7.2.
Edit 2: I do not expect Regex from controller to be nothing but a string in View
The CategoryList action produce the data in the wrong format. Either you have to use jsonReader or change the code of CategoryList action.
The standard format of items from the rows part of the server response should be like the following
{"id" :"1", "cell": ["cell11", "cell12", "cell13"]}
If the first column Id is unique and can be used as the id of the row you can use just array or strings instead:
rows = (from cat in categories.Take(10)
select new[] {
cat.Id.ToString(),
cat.Name,
cat.LastUpdate.ToString(),
cat.ValidationXSD
}).ToArray()
In the jqGrid you should add key: true to the list of the properties of the column 'Id' and add the following jqGrid option
jsonReader: { cell: "" }
I recommend you to play with the demo project from my old answer or with it's modification from another answer.

Categories