jqGrid for MVC not all values coming through on edit - asp.net-mvc

I'm trying to implement a jqGrid with MVC.
The Model is:
public class InvoiceHeader
{
public int id { get; set; }
public DateTime invdate { get; set; }
public int clientid { get; set; }
public decimal amount { get; set; }
[Display(Name = "Invoice Number:")]
public int tax { get; set; }
public decimal total { get; set; }
[Required(ErrorMessage = "Note is a required field.")]
[Display(Name = "Note:")]
public string note { get; set; }
public int PaymentTypeId { get; set; }
public string CreatedByUsername { get; set; }
public virtual PaymentType PaymentType { get; set; }
}
My View is:
#model JQGRID.Models.InvoiceHeader
#{
ViewBag.Title = "Home Page";
}
#*<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />*# <title>My First
Grid</title>#*<link rel="stylesheet" type="text/css" media="screen" href="css/ui-lightness/jquery-ui-1.7.1.custom.css" />*#
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/css/ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" media="screen" href="../../Scripts/css/ui.multiselect.css" />
#*<link rel="stylesheet" type="text/css" media="screen" href="../../Content/themes/ui-lightness/jquery-ui-1.8.14.custom.css" />*#
<style>
html, body
{
margin: 0;
padding: 0;
font-size: 75%;
}
</style>
<script src="../../Scripts/js/jquery-1.5.2.min.js" type="text/javascript"></script>
<script src="../../Scripts/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="../../Scripts/js/jquery.jqGrid.min.js" type="text/javascript"></script>
#*<script src="../../Scripts/src/grid.inlinedit.js" type="text/javascript"></script>*#
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData/',
datatype: 'json',
mtype: 'POST',
colNames: ['id', 'note', 'tax', 'PaymentType', 'CreatedByUsername', 'Actions'],
colModel: [
{ name: 'id', index: 'id', hidden: true, editable: false },
{ name: 'note', index: 'note', width: 40,align:'center', editable: true, editrules: { required : true } },
{ name: 'tax', index: 'tax', width: 400, align: 'center', editable: true, editrules: { required : true } },
{ name: 'PaymentTypeId', index: 'PaymentTypeId', width: 400, align: 'center', editable: true, edittype:"select",
editoptions: { dataUrl: '/Home/PaymentTypes/' }},
{ name: 'CreatedByUsername', index: 'CreatedByUsername', hidden: true, editable: false },
{ name: 'act',index:'act',width:55,align:'center',sortable:false,formatter:'actions',
formatoptions:{
keys: true, // we want use [Enter] key to save the row and [Esc] to cancel editing.
beforeSubmit:function(postdata, formid) {
alert("Hi");
jQuery("#ValidationSummary").show('slow');
},
},}
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '',
caption: 'My first grid',
editurl: '/Home/Save/'
});
jQuery("#list").navGrid('#pager', { edit: false, search: false, add: true });
});
</script>
#using (Html.BeginForm()) {
#Html.ValidationSummary()
<table id="list">
</table>
<div id="pager">
</div>}
As you can see on Save the following method in the controller is called:
public void Save(InvoiceHeader invoiceHeader)
{
if (ModelState.IsValid) {
...
try {
context.SaveChanges();
}
catch (Exception ex) {
}
}
}
What I don't understand is why when you enter this method and check invoiceHeader properties the id property is populated but the CreatedByUsername property is not populated.
I really need this property populated to save.
Could someone please explain to me why this is and how I can get CreatedByUsername populated?

Did you check the values of the Id object in your Save action? They should be the row id in the grid, not the actual Id of the object you're editing.
To prevent this, you should try adding columns for the Id and the CreatedByUserName columns and make them invisible. Also, add a key:true value to your Id column. That way, while editing, the values will get populated from those columns.

Related

checkBox filter table when field is null

I have a table with orders, one of the columns is "Tracking number"
Added a checkbox to so user can choose when to see all orders or just orders without tracking numbers.
here is the checkbox in view :
<div id="TrackingNumber">
<input type="checkbox" name="pos" value=true/>Show All
</div>
the javascript called is :
<script>
$(document).ready(function () {
$.fn.dataTable.ext.search.push(
function (settings, searchData, index, rowData, counter) {
var positions = $('input:checkbox[name="pos"]:checked').map(function () {
return this.value;
}).get();
if (positions.length === 0) {
return true;
}
if (positions.indexOf(searchData[1]) !== -1) {
return true;
}
return false;
}
)
var table = $('#tblData').DataTable();
$('input:checkbox').on('change', function () {
table.draw();
});
});</script>
when checkbox is checked it shows 0 records and when unchecked it shows all.
i want it to show all records when checkbox is checked and show only records WITHOUT tracking numbers
when Unchecked,
Help will be much appreciated :)
Here is a demo:
View:
<table id="tblList" class="table table-striped table-bordered" style="width:100%">
<div>
<input type="checkbox" id="pos" checked="checked"/>Show All
</div>
<thead class="thead-dark">
<tr class="table-info">
<th>pal</th>
<th>via</th>
<th>con</th>
<th>TrackingNumber</th>
</tr>
</thead>
</table>
#section scripts{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(function () {
var url = "GetAllPakingList";
LoadPack(url);
})
function LoadPack(url) {
$('#tblList').DataTable({
destroy: true,
ajax: {
url: url,
},
columns: [
{ "data": "pal", responsivePriority: 1, "searchable": true },
{ "data": "via", responsivePriority: 2, "searchable": true },
{ "data": "con", responsivePriority: 3, "searchable": true },
{ "data": "trackingNumber", responsivePriority: 4, "searchable": true },
],
});
};
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var trackingNumber = data[3];
if ($('#pos').prop("checked") != true && trackingNumber!="") {
return false;
} else {
return true;
}
}
);
$('input:checkbox').on('change', function () {
var table = $('#tblList').DataTable();
table.draw();
});
</script>
}
ListOutput:
public class ListOutput
{
public string pal { get; set; }
public string via { get; set; }
public string con { get; set; }
public string TrackingNumber { get; set; }
}
result:

JS grid not showing in Partial View MVC

In my project am showing js grid from partial view. so tried like this
View
<div id="searchgrid" class="col-lg-12">
#Html.Partial("ResultGrid", new List<SCM_MVC.Models.User>(), new ViewDataDictionary(this.ViewData) { { "index" , ViewData["Form"] } })
</div>
<script src="~/assets/js/jquery-1.10.2.js"></script>
<script>
var url = '#Url.Action("ResultGrid", "User", new { xEdit = ViewData["Form"]})';
$('#btnloadgrid').click(function () {
$('#searchgrid').load(url);
})
</script>
Partial View
#model IEnumerable<SCM_MVC.Models.User>
#{
/**/
/**/
#section head {
#*<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/demos.css" />*#
<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/jsgrid.css" />
<link rel="stylesheet" type="text/css" href="~/SCM/jsgrid/css/theme.css" />
<script src="~/SCM/jsgrid/js/jquery-1.8.3.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.core.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.load-indicator.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.load-strategies.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.sort-strategies.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.field.js"></script>
<script src="~/SCM/jsgrid/src/jsgrid.core.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.text.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.number.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.select.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.checkbox.js"></script>
<script src="~/SCM/jsgrid/src/fields/jsgrid.field.control.js"></script>
}
/**/
<table id="jsGrid"></table>
#section scripts {
<script src="http://js-grid.com/js/jsgrid.min.js"></script>
<script>
$(function () {
$("#jsGrid").jsGrid({
height: "70%",
width: "100%",
filtering: true,
editing: true,
inserting: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete the user?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "/api/data",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "/api/data",
data: item,
dataType: "json"
});
},
updateItem: function (item) {
return $.ajax({
type: "PUT",
url: "/api/data/" + item.ID,
data: item,
dataType: "json"
});
},
deleteItem: function (item) {
return $.ajax({
type: "DELETE",
url: "/api/data/" + item.ID,
dataType: "json"
});
}
},
fields: [
{ name: "user_id", title: Resources.Resource.user_id, type: "text", width: 150 },
{ name: "username", title: Resources.Resource.user_name, type: "text", width: 50 },
{ name: "mailid", title: Resources.Resource.mailid, type: "text", width: 200 },
{ name: "role", title: Resources.Resource.role, type: "text", width: 50 },
{ name: "dept", title: Resources.Resource.dept, type: "text", width: 100 },
{ name: "designation", title: Resources.Resource.designation, type: "text", width: 100 },
{ name: "city", title: Resources.Resource.city, type: "text", width: 100 },
{ name: "country", title: Resources.Resource.country, type: "text", width: 100 },
{ type: "control" }
]
});
});
</script>
}
}
DataController
namespace SCM_MVC.Controllers
{
public class DataController : ApiController
{
// GET: Data
public IEnumerable<object> Get()
{
//ClientFilter filter = GetFilter();
//var result = DB.Client.Where(c =>
// (String.IsNullOrEmpty(filter.Name) || c.Name.Contains(filter.Name)) &&
// (String.IsNullOrEmpty(filter.Address) || c.Address.Contains(filter.Address)) &&
// (!filter.Married.HasValue || c.Married == filter.Married) &&
// (!filter.Country.HasValue || c.Country == filter.Country)
//);
Models.User xuser = new Models.User();
List<Models.User> xuserlist = new List<Models.User>();
//if (ViewData["index"] == null)
//{
// ViewData["index"] = xEdit;
//}
xuser.UserId = "US-0001";
xuser.UserName = "Robert";
xuser.Mailid = "robert#gmail.com";
xuser.Role = "Admin";
xuser.Designation = "Sales Admin";
xuser.Dept = "Sales";
xuser.State = "Tamil Nadu";
xuser.Country = "India";
xuserlist.Add(xuser);
return xuserlist;
}
}
}
UserController
public ActionResult ResultGrid(string xEdit)
{
Models.User xuser = new Models.User();
List<Models.User> xuserlist = new List<Models.User>();
xuser.UserId = "US-0001";
xuser.UserName = "Robert";
xuser.Mailid = "robert#gmail.com";
xuser.Role = "Admin";
xuser.Designation = "Sales Admin";
xuser.Dept = "Sales";
xuser.State = "Tamil Nadu";
xuser.Country = "India";
xuserlist.Add(xuser);
return PartialView(xuserlist);
}
But in Screen its not showing. What am doing wrong here?
Thanks
Am using Visual Studio 2017 ASP.Net MVC

ASP.net Mvc 2.0 with JQGrid

I have to implement inline editing with combobox in JQGrid,and i have to populate data in combobox from database no hard coded value i have already written the view part and i am using Linq to Sql as model but not able to write controller for that. I have got one sample for that but in sample repository design pattern has been used and i have not to use that.So can any on help me to write thebcontroller part.
My view part is
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<link href="../../Content/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css" />
<link href="../../Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/JQGrid/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/jquery.jqGrid.src.js" type="text/javascript"></script>
<script src="../../Scripts/JQGrid/grid.locale-en.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Grid").jqGrid(
{ url: '/Default/GetData',
datatype: 'json',
mtype: 'GET',
colNames: ['Id', 'UserName', 'Organization', 'Report Type', 'EmailID', 'Action'],
colModel: [
{ name: 'Id', index: 'Id', align: 'center', width: 30, editable: false },
{ name: 'UserName', index: 'UserName', align: 'center', width: 150, editable: true, edittype: 'select', formatter: 'select', editoptions: { dataUrl: '/Default/UserSelect' } },
{ name: 'Organization', index: 'Organization', align: 'center', width: 200, editable: true, edittype: 'select', formatter: 'select', editoptions: { dataUrl: '/Default/OrganizationSelect' }, editrules: { required: true} },
{ name: 'Report Type', index: 'Report Type', align: 'center', width: 200, editable: true, edittype: 'select', editoptions: { value: 'MN:Monthly; YR:Yearly', defaultValue: 'Montyhly'} },
{ name: 'EmailID', index: 'EmailID', align: 'center', width: 250, editable: true, edittype: 'text', editoptions: { size: 30, maxlength: 40} },
{ name: 'act', width: 100, align: 'center', sortable: false, formatter: 'actions', formatoptions: { keys: true, editbutton: true}}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "asc",
viewrecords: true,
caption: 'Regen Users'
});
});
</script>
<title>Index</title>
</head>
<body>
<div>
<table id="Grid">
</table>
</div>
<div id="pager">
</div>
</body>
</html>
And my get data controller is as
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Important.Models;
using System.Linq.Dynamic;
namespace Important.Controllers
{
public class DefaultController : Controller
{
RegenDataContext db = null;
public DefaultController()
{
db = new RegenDataContext();
}
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult GetData(string sidx, string sord, int page, int rows)
{
var pageIndex = Convert.ToInt32(page) - 1;
var pageSize = rows;
var totalRecords = db.rptUsers.Count();
var totalPages = (int)Math.Ceiling(totalRecords / (float)pageSize);
var user = db.rptUsers
.OrderBy(sidx + " " + sord)
.Skip(pageIndex * pageSize)
.Take(pageSize).AsQueryable();
var jsonData = new
{
rows = (
from rptUser u in user
select new
{
i=u.ID,
cell=new string[]{u.ID.ToString(),u.UserName, u.UserOrganizationID.ToString()}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public ActionResult UserSelect()
{
return View();
}
public ActionResult OrganizationSelect()
{
return View();
}
}
}
help me to write controller action for data url UserSelect.
As per below jqGrid documentation
Setting the editoptions dataUrl parameter: The editoptions dataUrl parameter is valid only for element of edittype:select. The dataUrl parameter represent the url from where the html select element should be get.
When this option is set, the element will be filled with values from the AJAX request. The data should be a valid HTML select element with the desired options - something like:
<select>
<option value='1'>One</option>
<option value='2'>Two</option>
...
</select>
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:common_rules#edittype
something like below: NOT TESTED
public JsonResult UserSelect()
{
List<User> users=db.GetUsers();
return Json(users,JsonRequestBehavior.AllowGet);
}
View: jqGrid
editoptions: { dataUrl:'<%= Url.Action("xxxx","xxxx") %>',
buildSelect: function(data) {
var response = jQuery.parseJSON(data.responseText);
var s = '<select>';
if (response && response.length) {
for (var i = 0, l=response.length; i<l ; i++) {
var ri = response[i];
s += '<option value="'+ri+'">'+ri+'</option>';
}
}
return s + "</select>";
}
}
Check this:
ASP.NET MVC $.post call returning string...need help with format for jqGrid

Error during database connection with jqgrid

I'm trying to connect to database from jqgrid. I have this bug in the controller, does anyone know how to fix it?
Component LINQ to Entities does not recognize the method 'System.String ToString () "and you can not translate it to express the warehouse.
When given data rigidly works.
new {id = 1, cell = new[] {"1", "zzzzzz", "xxxxxx"}}
In addition, I would like to ask how to add edit to jqgrid?
View
<asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:content contentplaceholderid="HeadContent" runat="server">
<link href="/Content/jquery-ui-1.8.7.css" rel="stylesheet" type="text/css" />
<link href="/Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="/Scripts/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="/Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#list").jqGrid({
url: '/Home/LinqGridData/',
datatype: 'json',
mtype: 'GET',
colNames: ['CatID', 'CatName', 'Age'],
colModel: [
{ name: 'CatID', index: 'CatID', width: 40, align: 'left' },
{ name: 'CatName', index: 'CatName', width: 40, editable: true, align: 'left' },
{ name: 'Age', index: 'Age', width: 400, align: 'left' }],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/scripts/themes/coffee/images',
caption: 'My first grid'
});
jQuery("#list").jqGrid('navGrid', "#pager", { edit: true, add: true, del: true });
jQuery("#list").jqGrid('inlineNav', "#pager");
});
</script>
</asp:content>
<asp:content contentplaceholderid="MainContent" runat="server">
<h2>My Grid Data</h2>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
</asp:content>
Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MvcApplication2.Models
{
public class Cat
{
[Key]
public int CatID { get; set; }
public string CatName { get; set; }
public string Age { get; set; }
}
}
Controller
public ActionResult LinqGridData(string sidx, string sord, int page, int rows)
{
var context = new CatEntities();
var jsonData = new
{
total = 1, //todo: calculate
page = page,
records = context.Cats.Count(),
rows = (
from question in context.Cats
select new
{
i = question.CatID,
cell = new string[] { question.CatID.ToString(), question.CatName, question.Age }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I think it's because the question for a moment it is sent to the database,
You can't send this:
question.CatID.ToString()
to SQL Server because it doesn't know what to do with the method call. If you force enumeration of the set first you can make use of .NET methods in memory:
from question in context.Cats.ToList()
The problem is going to be balancing performance. If the Cats unfiltered set is large performance will suffer as the entire table is loaded into memory. In your case you probably won't notice a difference as you're invoking ToArray() later anyway.
If possible, use Skip() and Take() to implement paging and keep your sets small.
You should also consider storing the result in a variable so that you can reference it for your rows and records properties rather than hitting the context twice.

How to use Kendo UI MVC Extensions with require js?

I have a controller that looks like this:
using System.Collections.Generic;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
namespace KendoMvcApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetData([DataSourceRequest] DataSourceRequest req)
{
var products = CreateProducts();
var result = products.ToDataSourceResult(req);
return Json(result);
}
private static IEnumerable<Product> CreateProducts()
{
for (int i = 1; i <= 20; i++)
{
yield return new Product
{
ProductId = i,
ProductName = "Product " + i,
ProductPrice = i * 2.5
};
}
}
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public double ProductPrice { get; set; }
}
}
And a view that looks like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo.default.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/require.js"></script>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
require.config({
baseUrl : '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui'
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
require(['jquery', 'kendo/kendo.grid.min'], function ($) {
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: {
schema: {
data: 'Data',
total: 'Total',
aggregates: 'AggregateResults',
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
ProductPrice: { type: "number" }
}
}
},
transport: {
read: {
url: "#Url.Action("GetData", "Home")",
dataType: "json",
method: "post"
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true,
type: "aspnetmvc-ajax"
},
sortable: {
mode: "single"
},
columns: ["ProductName", "ProductPrice"],
scrollable: false,
pageable: true
});
});
});
</script>
</body>
</html>
And my directory structure is:
Scripts/kendo-ui/* (all the kendo files, including the mvc one)
Scripts/require.js
Scripts/jquery-2.0.3.min.js
which nearly works except that server-side sorting doesn't get applied.
This is because the kendo.aspnet.mvc.min.js file is never downloaded (of course, as require JS doesn't know anything about it) so to remedy that I tried this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo.default.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/require.js"></script>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
require.config({
baseUrl: '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui',
'kendo-mvc': 'kendo/kendo.aspnetmvc.min'
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
require(['jquery', 'kendo-mvc', 'kendo/kendo.grid.min'], function ($) {
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: {
schema: {
data: 'Data',
total: 'Total',
aggregates: 'AggregateResults',
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
ProductPrice: { type: "number" }
}
}
},
transport: {
read: {
url: "#Url.Action("GetData", "Home")",
dataType: "json",
method: "post"
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true,
type: "aspnetmvc-ajax"
},
sortable: {
mode: "single"
},
columns: ["ProductName", "ProductPrice"],
scrollable: false,
pageable: true
});
});
});
</script>
</body>
</html>
But that produced this error:
And attempted to load the js files thus:
The red spots are 404 not found as it is looking for the js files in a folder called kendo under the scripts folder.
So then I thought I would try including the all version instead so I tried this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="~/Content/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo.default.min.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/require.js"></script>
</head>
<body>
<div id="grid"></div>
<script type="text/javascript">
require.config({
baseUrl: '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui/kendo.all.min',
'kendo-mvc': 'kendo-ui/kendo.aspnetmvc.min'
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
require(['jquery', 'kendo', 'kendo-mvc'], function ($) {
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: {
schema: {
data: 'Data',
total: 'Total',
aggregates: 'AggregateResults',
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
ProductPrice: { type: "number" }
}
}
},
transport: {
read: {
url: "#Url.Action("GetData", "Home")",
dataType: "json",
method: "post"
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true,
type: "aspnetmvc-ajax"
},
sortable: {
mode: "single"
},
columns: ["ProductName", "ProductPrice"],
scrollable: false,
pageable: true
});
});
});
</script>
</body>
</html>
But that produced these errors:
And attempted to load the js files thus:
In this case - the red spots are 404 not found as it is looking for the files directly under the Scripts folder.
So here is my question:
How can I include said file in a require JS type scenario?
Aside: I would like to be using the kendo.all.min file and not the separate ones as I want to use knockout-kendo in the future and that seems to not work with the separate file but if the only way to make this work is to use the separate file approach, that is fine.
It took me a while to get your code working but after having been fiddling around with it a little I managed to get the sorting to work with just a tiny little change in your original code.
The only thing I changes was on the require line where I added the mvc file as well. Then all the paths became correct and it all worked out fine.
['jquery', 'kendo/kendo.grid.min', 'kendo/kendo.aspnetmvc.min']
In my code I've used "Kendo UI for ASP.NET MVC Q2 2013" with the jQuery.min.js file that was included in that package. The complete View code then becomes:
<script type="text/javascript">
require.config({
baseUrl : '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui'
},
shim: {
'jquery': {
exports: 'jQuery'
}
}
});
require(['jquery', 'kendo/kendo.grid.min', 'kendo/kendo.aspnetmvc.min'], function ($) {
$(document).ready(function () {
$('#grid').kendoGrid({
dataSource: {
schema: {
data: 'Data',
total: 'Total',
aggregates: 'AggregateResults',
model: {
id: "ProductId",
fields: {
ProductName: { type: "string" },
ProductPrice: { type: "number" }
}
}
},
transport: {
read: {
url: "#Url.Action("GetData", "Home")",
dataType: "json",
method: "post"
}
},
pageSize: 10,
serverPaging: true,
serverSorting: true,
type: "aspnetmvc-ajax"
},
sortable: {
mode: "single"
},
columns: ["ProductName", "ProductPrice"],
scrollable: false,
pageable: true
});
});
});
</script>
I hope it'll work in your code as well.
Let's try building up from a minimal working version. You said you have the following in the directory:
Scripts/kendo-ui/* (all the kendo files, including the mvc one)
Scripts/require.js
Scripts/jquery-2.0.3.min.js
To get that to load all the dependencies, you might try something like this:
<html>
<body>
<script type="text/javascript" src="~/Scripts/require.js"></script>
<script type="text/javascript">
require.config({
baseUrl: '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo': 'kendo-ui/kendo.all.min',
'kendo-mvc': 'kendo-ui/kendo.aspnetmvc.min'
},
shim: {
'jquery': {
exports: 'jQuery'
},
'kendo-mvc' : {
deps: ['kendo'] //kendo needs to be loaded before kendo-mvc?
}
}
});
require(['jquery', 'kendo', 'kendo-mvc'], function ($) {
});
</script>
</body>
</html>
I played around with putting it in a jsFiddle, but ran into a number of problems (Kendo actually requires jQuery 1.9.0, etc.) that you can probably resolve on your own.
The key seems to be that your last version is loading kendo.data, kendo.combobox, and a bunch of other files that aren't referenced anywhere. Figuring out where those requests came from would help solve this mystery.
Update:
Here's one possibility. If kendo-mvc is loading dependencies like this:
["./kendo.data.min","./kendo.combobox.min","./kendo.multiselect.min","./kendo.‌​validator.min"]
Then it may fail because RequireJS looks for dependencies relative to the name of the module, which has been aliased as kendo-mvc. Let's try not renaming it (see below), and see if that works:
<script type="text/javascript">
require.config({
baseUrl: '#Url.Content("~/Scripts")',
paths: {
'jquery': 'jquery-2.0.3.min',
'kendo-ui/kendo': 'kendo-ui/kendo.all.min',
'kendo-ui/kendo-mvc': 'kendo-ui/kendo.aspnetmvc.min'
},
...
require(['jquery', 'kendo-ui/kendo', 'kendo-ui/kendo-mvc'], function ($) {
});

Resources