Hi I'm using Kendo grid with dropdownlist, I followed the demo in http://demos.kendoui.com/web/grid/foreignkeycolumn.html
but Im recieving this error "DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Id'".
Could anyone help me to make my code work without error?
here is my viewModel :
public class AccountingViewModel
{
private string _code = string.Empty;
private string _description = string.Empty;
public int Id
{
get;set;
}
public string Code
{
get { return _code; }
set { _code = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public int MajorCategoryId
{
get;set;
}
public SelectList MajorCategories
{
get;set;
}
}
Here is my Controller :
public ActionResult Index()
{
var majorCategory = new SelectList(new[]
{
new {Id="1",Name="Category1"},
new{Id="2",Name="Category2"},
new{Id="3",Name="Category3"},
},
"Id", "Name", 1);
ViewData["majorCategories"] = majorCategory;
return View(accountingService.GetAllAccountings());
}
Here is my Index View:
#model IEnumerable < PPMS.Model.ViewModels.AccountingViewModel >
< br/ >
< div class="k-grid" >
#(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Code);
columns.Bound(p => p.Description).Width(150);
columns.ForeignKey(p => p.MajorCategoryId, (System.Collections.IEnumerable)ViewData["majorCategories"], "Id", "Name")
.Title("MajorCategory").Width(150);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolBar =>
{
toolBar.Save();
toolBar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Groupable()
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("errorHandler"))
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Id).Editable(false);
model.Field(p => p.MajorCategoryId).DefaultValue(1);
})
.Create(create => create.Action("Create", "Accounting"))
.Read(read => read.Action("Index", "Accounting"))
.Update(update => update.Action("Edit", "Accounting"))
.Destroy(destroy => destroy.Action("Delete", "Accounting"))
)
)
</div>
<br/>
<script type="text/javascript">
function errorHandler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>
I have updated my view into and is now binding the selectlist the problem now its displaying textbox inside the grid instead of a dropdownlist.. here is my updated Index view:
Here is my Index View:
#model IEnumerable < PPMS.Model.ViewModels.AccountingViewModel >
< br/ >
< div class="k-grid" >
#(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Code);
columns.Bound(p => p.Description).Width(150);
columns.ForeignKey(p => p.MajorCategoryId, (System.Collections.IEnumerable)ViewData["majorCategories"], "Value", "Text")
.Title("MajorCategory").Width(150);
columns.Command(command => command.Destroy()).Width(110);
})
.ToolBar(toolBar =>
{
toolBar.Save();
toolBar.Create();
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Filterable()
.Groupable()
.Pageable()
.Scrollable()
.HtmlAttributes(new { style = "height:430px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.PageSize(20)
.ServerOperation(false)
.Events(events => events.Error("errorHandler"))
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Id).Editable(false);
model.Field(p => p.MajorCategoryId).DefaultValue(1);
})
.Create(create => create.Action("Create", "Accounting"))
.Read(read => read.Action("Index", "Accounting"))
.Update(update => update.Action("Edit", "Accounting"))
.Destroy(destroy => destroy.Action("Delete", "Accounting"))
)
)
</div>
<br/>
<script type="text/javascript">
function errorHandler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>
The foreign dropdown list should contain items which have a "value" and "text" property ?
Like:
var categories = [{
"value": 1,
"text": "Beverages"
},{
"value": 2,
"text": "Condiments"
}
}];
Related
I seem to be having a unique issue in my kendo grid. I have searched everywhere and tried multiple things but no luck. I need to bind my "HoldReason" dropdownlist to the kendo grid and the "HoldReason" will always be null or nothing selected initially. Currently my grid shows 'undefined' in that grid column.
ViewModel:
public class PaymentDetailTerm
{
public PaymentDetailTerm()
{
}
private int? holdReasonId;
private bool holdFlag;
private decimal disbursed;
private SysHoldReason holdReason;
//some properties omitted
[Display(Name = "Disbursed")]
[NonNegative]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:c}")]
public decimal Disbursed
{
get
{
return disbursed;
}
set
{
disbursed = value;
}
}
[Display(Name = "Hold")]
[BoolFieldRequiredWhenInt("HoldReasonId")]
public bool HoldFlag
{
get
{
return holdFlag;
}
set
{
holdFlag = value;
}
}
[Display(Name = "Hold Reason")]
[IDFieldRequiredWhenBool("HoldFlag")]
public int? HoldReasonId
{
get
{
return holdReasonId;
}
set
{
holdReasonId = value;
}
}
[UIHint("HoldReasonEditor")]
public SysHoldReason HoldReason
{
get
{
if (holdReason == null || holdReason.HoldReasonId == 0)
{
return new SysHoldReason() { HoldReasonId = 0, HoldReasonTitle = string.Empty };
}
else return holdReason;
}
set { holdReason = value; }
}
}
TemplateEditor "HoldReasonEditor":
#using System.Collections
#using Kendo.Mvc.UI
<kendo-dropdownlist name="HoldReasonId" bind-to="ViewBag.HoldReasonId" Auto-Width="true" option-label=" " datatextfield="Text" datavaluefield="Value" value-primitive="true"></kendo-dropdownlist>
Controller (these are the only two statements concerning the dropdown in question):
ViewData["HoldReasonId"] = new SelectList(_context.SysHoldReason.Where<SysHoldReason>(x => x.SiteId == 99 || x.SiteId == _user.SiteId), "HoldReasonId", "HoldReasonTitle");
ViewData["HoldReasonCollection"] = new SelectList(_context.SysHoldReason.Where<SysHoldReason>(x => x.SiteId == 99 || x.SiteId == _user.SiteId), "HoldReasonId", "HoldReasonTitle");
I use the HoldReasonCollection as a hidden field so I can set the information correctly later on grid save. SysHoldReason model contains HoldReasonId and HoldReasonTitle properties (and more, but those are the only ones I'm concerned with).
And the kendo grid defined in my view:
#(Html.Kendo().Grid<eCLERC.ViewModels.PaymentDetailTerm>(Model.PaymentDetailTerms)
.Name("TermGrid")
.DataSource(ds => ds
.Ajax()
.ServerOperation(false)
.Model(m =>
{
m.Field(d => d.TermTypeTitle).Editable(false);
m.Field(d => d.PayeePartyName).Editable(false);
m.Field(d => d.PayoffBalance).Editable(false);
m.Field(d => d.PeriodicAmount).Editable(false);
m.Field(d => d.UnpaidBalance).Editable(false);
m.Field(d => d.ClerkFeeFlag).Editable(false);
m.Field(d => d.HoldFlag).Editable(true);
m.Field(d => d.HoldReasonId).Editable(true);
m.Field(d => d.HoldReason);
//m.Field(p => p.HoldReason).DefaultValue(ViewData["HoldReasonId"] as eCLERC.Models.DB.SysHoldReason);
})
)
.Columns(columns =>
{
columns.Bound(e => e.TermTypeTitle).Width(110).Title("Term Type");
columns.Bound(e => e.PayeePartyName).Width(110).Title("Payee");
columns.Bound(e => e.PayoffBalance).Width(110);
columns.Bound(e => e.PeriodicAmount).Width(110); //TODO: Nikki - what is recap amount
columns.Bound(e => e.UnpaidBalance).Width(100);
columns.Bound(e => e.ClerkFeeFlag).Width(100);
columns.Bound(e => e.Disbursed).Width(100);
columns.Bound(e => e.HoldFlag).Width(100);
columns.Bound(e => e.HoldReason).EditorTemplateName("HoldReasonEditor").ClientTemplate("#=HoldReason.Text#");
})
.Sortable()
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Events(x => { x.Save("function(e){onGridSave(e)}"); })
.Scrollable()
.HtmlAttributes(new { style = "height:350px" }))
The dropdown works and if I select a value, then I see the HoldReason title value as I expect to, but I just can't figure out how to fix the 'undefined' text that shows initially. And likewise, if I want to set the dropdown back to the option label (" "), the dropdown control shows a validation that HoldReasonId required.
Finally!! So, I figured this out. First, the HoldReasonId required error. I was binding that control to a database model for the whole code table, id, title, description, etc. This was also the model that controlled the data entry for that code table, so the id value was required, which was why I was getting that error. It was giving me the validation from the SysHoldReason database model. I fixed this by creating a separate view model, for ViewSysHoldReason, which only contains a nullable HoldReasonId value and a string HoldReasonTitle value.
public class ViewSysHoldReason
{
public int? HoldReasonId { get; set; }
public string HoldReasonTitle { get; set; }
}
Next, I updated my PaymentDetailTerm view model to use this for the editor instead of the whole code table database model as before.
public class PaymentDetailTerm
{
public PaymentDetailTerm()
{
}
private int? holdReasonId;
private bool holdFlag;
private decimal disbursed;
private ViewSysHoldReason viewSysHoldReason;
//some properties omitted
[Display(Name = "Disbursed")]
[NonNegative]
[DataType(DataType.Currency), DisplayFormat(DataFormatString = "{0:c}")]
public decimal Disbursed
{
get
{
return disbursed;
}
set
{
disbursed = value;
}
}
[Display(Name = "Hold")]
[BoolFieldRequiredWhenInt("HoldReasonId")]
public bool HoldFlag
{
get
{
return holdFlag;
}
set
{
holdFlag = value;
}
}
[Display(Name = "Hold Reason")]
[IDFieldRequiredWhenBool("HoldFlag")]
public int? HoldReasonId
{
get
{
return holdReasonId;
}
set
{
holdReasonId = value;
}
}
[UIHint("HoldReasonEditor")]
public ViewSysHoldReason HoldReason
{
get
{
if (viewSysHoldReason == null || viewSysHoldReason.HoldReasonId == 0)
{
return new ViewSysHoldReason() { HoldReasonId = 0, HoldReasonTitle = string.Empty };
}
else return viewSysHoldReason;
}
set { viewSysHoldReason = value; }
}
}
The last property above for HoldReason is all that changed here. Next, I updated the grid for display as shown here:
#(Html.Kendo().Grid<eCLERC.ViewModels.PaymentDetailTerm>(Model.PaymentDetailTerms)
.Name("TermGrid")
.DataSource(ds => ds
.Ajax()
.ServerOperation(false)
.Model(m =>
{
m.Field(d => d.TermTypeTitle).Editable(false);
m.Field(d => d.PayeePartyName).Editable(false);
m.Field(d => d.PayoffBalance).Editable(false);
m.Field(d => d.PeriodicAmount).Editable(false);
m.Field(d => d.UnpaidBalance).Editable(false);
m.Field(d => d.ClerkFeeFlag).Editable(false);
m.Field(d => d.HoldFlag).Editable(true);
m.Field(d => d.HoldReasonId).Editable(true);
m.Field(d => d.HoldReason);
})
)
.Columns(columns =>
{
columns.Bound(e => e.TermTypeTitle).Width(110).Title("Term Type");
columns.Bound(e => e.PayeePartyName).Width(110).Title("Payee");
columns.Bound(e => e.PayoffBalance).Width(110);
columns.Bound(e => e.PeriodicAmount).Width(110); //TODO: Nikki - what is recap amount
columns.Bound(e => e.UnpaidBalance).Width(100);
columns.Bound(e => e.ClerkFeeFlag).Width(100);
columns.Bound(e => e.Disbursed).Width(100);
columns.Bound(e => e.HoldFlag).Width(100);
columns.ForeignKey(p => p.HoldReason, (System.Collections.IEnumerable)ViewData["HoldReasonId"], "Value", "Text")
.EditorViewData(new {HoldReasonId = (System.Collections.IEnumerable)ViewData["HoldReasonId"]})
.EditorTemplateName("HoldReasonEditor").ClientTemplate("#=HoldReason.Value > 0 ? HoldReason.Text : '' #")
.Title("Hold Reason")
.Width(110);
})
.Sortable()
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Events(x => { x.Save("function(e){onGridSave(e)}"); x.CellClose("function(e){onCellClose(e)}"); })
.Scrollable()
.HtmlAttributes(new { style = "height:350px" }))
Note that I added an event for CellClose. This is because I wanted to catch the editor when a user selected the optionlabel = " " to remove a HoldReason from the grid. I could not figure out how to set that value back to empty once a user selected a value from the dropdown, so the CellClose was my solution to that.
function onCellClose(e) {
var grid = $("#TermGrid").data("kendoGrid");
var fieldName = grid.columns[e.container.index()].field;
if (fieldName == "HoldReason" && e.container.find("input").val() == "") {
e.model.HoldReasonId = 0;
e.model.HoldReason.Value = 0;
e.model.HoldReason.Text = "";
}
}
The model would not be set correctly without the onGridSave event though so I feel like I should show that code as well. I did not share it on my original post.
function onGridSave(e) {
e.preventDefault();
var grid = $("#TermGrid").data("kendoGrid");
var fieldName = grid.columns[e.container.index()].field;
if (fieldName == "HoldReason") {
$('#HoldReasonCollection').data('kendoDropDownList').value(e.container.find("input").val());
e.model.HoldReasonId = e.values["HoldReason.HoldReasonId"];
e.model.HoldReason = $('#HoldReasonCollection').data('kendoDropDownList').dataItem();
}
if (fieldName == "Disbursed") {
e.model.Disbursed = e.container.find("input").val();
}
if (fieldName == "HoldFlag" && e.model.HoldFlag == true) {
e.model.HoldFlag = false;
}
else if (fieldName == "HoldFlag" && e.model.HoldFlag == false) {
e.model.HoldFlag = true;
}
}
I am using Kendo Grid. The problem I am facing is that I am not able to filter the datetime by selecting any option from filter.
Here is my code:
#(Html.Kendo()
.Grid<IssueViewModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.IssuePostedAt).Format("{0:dd.MM.yyyy hh:mm:ss}").Filterable(filterable => filterable.UI("orderDateFilter")).Title("Posted")
.ClientTemplate("#:kendo.toString(data.IssuePostedAt, \"dd.MM.yyyy hh:mm:ss\")#");
})
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.ButtonCount(5))
.Events(events => events.DataBound("onGridDataBound"))
.Filterable(filterable => filterable
.Enabled(true)
.Extra(false)
.Operators(operators => operators.ForString(str => str.Clear().Contains("Содержит")))
)
.DataSource(dataSource => dataSource
.WebApi()
.Model(model => model.Id(i => i.Issue.Id))
.Sort(sort => sort.Add(i => i.IssuePostedAt).Descending())
.Read(read => read.Url("/issue/gridData"))
.PageSize(20)
)
JavaScript:
function orderDateFilter(element) {
element.kendoDateTimePicker({
format: "dd.MM.yyyy hh:mm:ss",
timeFormat: "hh:mm:ss"
});
}
This is code in the controller:
[HttpGet]
[Route("gridData")]
public async Task<ActionResult> GridData([ModelBinder(typeof(DataSourceRequestModelBinder))] DataSourceRequest request)
{
var filterByUser = HttpContext.GetReferrerParam("name");
var gridData = await IssuesRepository.Instance.Get(filterByUser); // get all data from DB
var results = gridData.ToDataSourceResult(request);
return Json(results);
}
DateTime filtering doesn't work at all. gridData.ToDataSourceResult(request); always return empty result.
I will be thankful if anybody could help me out in solving my issue. Thanks in advance.
In a Kendo grid (v2013.3) I want to auto-save a row when the user moves to a different row. So I code the change event, which fires when the row selection is changed, to call grid.saveChanges(). Then I re-select the row that we changed to (because the saveChanges seems to have canceled the row selection.) Finally, I call grid.editRow(row) so that the new row will be in edit mode.
This almost works fine. When the user changes a value in a row A, then clicks away to row B, the save action properly occurs and the web app sees the changed value. However, the UI itself reverts to the old value. This occurs because of the call to grid.editRow().
I suspect that Kendo is doing a cancel behind the scenes, even though the changed data is already saved.
Suggestions on how to address this problem? Here's the change handler:
ViLinking.gridItemSelected = function (e) {
var row = ViLinking.getSingleSelectedRow(this);
if (row == null) {
return;
}
var dataItem = this.dataItem(row);
if (dataItem == ViLinking.currentDataItem) {
return;
}
// apparently the row reference does not survive saveChanges() so prepare to re-get it.
ViLinking.currentDataItem = dataItem;
var dataUid = row.attributes["data-uid"];
var table = $(row).closest("table");
ViLinking.setKendoUpdateContentType(this);
this.saveChanges();
row = table.find('tr[data-uid="' + dataUid.value + '"]');
this.select(row);
this.editRow(row);
};
Here's the part of the view that generates the table (it's a child table)
<script id="ViDetailsTemplate" type="text/kendo-tmpl">
#(Html.Kendo().Grid<VendItemProxyForUi>()
.Name("details_#=ItemOid#")
.Columns(cs =>
{
cs.Bound(c => c.ItemOid).Hidden();
cs.Bound(c => c.VendorItemID);
cs.Bound(c => c.IsSplit);
cs.Bound(c => c.VendorItemName);
cs.Bound(c => c.VendorItemPackSize);
cs.Bound(c => c.IsCatchweight);
cs.Bound(c => c.IsApproved);
cs.Bound(c => c.UofMOidForUi).EditorTemplateName("UofmDdTemplate");//.ClientTemplate("#=UofMName#");
cs.Bound(c => c.UofMName);
cs.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(200);
}
)
.Selectable()
.Editable(edit => edit.Mode(GridEditMode.InLine))
.DataSource(ds => ds
.Ajax()
.Model(mdl =>
{
mdl.Id(vi => vi.VendorItemID);
mdl.Field(f => f.VendorItemID).Editable(false);
mdl.Field(f => f.VendorItemName).Editable(false);
mdl.Field(f => f.IsSplit).Editable(false);
mdl.Field(f => f.IsCatchweight).Editable(false);
mdl.Field(f => f.DiscontinueDate).Editable(false);
mdl.Field(f => f.IsRestricted).Editable(false);
mdl.Field(f => f.VendorItemPackSize).Editable(false);
mdl.Field(f => f.IsApproved).Editable(true);
mdl.Field(f => f.UofMName).Editable(true);
}
)
.Read(read => read.Action("GetVisForGi", "ViLinkingWorksheet", new { _msk = Model.MultiSessionKey, itemOid="#=ItemOid#"}))
.Update(update => update.Action("SyncModelFromUi", "ViLinkingWorksheet", new { _msk = Model.MultiSessionKey, itemOid="#=ItemOid#", delete=false}))
.Destroy(update => update.Action("SyncModelFromUi", "ViLinkingWorksheet", new { _msk = Model.MultiSessionKey, itemOid="#=ItemOid#",delete=true}))
)
//.HtmlAttributes(new { style = "height:100px;" })
.Events(ev =>
{
ev.Change("ViLinking.gridItemSelected");
ev.Cancel("ViLinking.saveOnCancel");
})
//.Navigatable()
.ToClientTemplate())
</script>
1- View
#(Html.Kendo().Grid<User>()
.Name("GridName")
.Columns(columns =>
{
...
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Pageable(p => p.PageSizes(new[] { 5, 10, 20, 50, 100 }))
.Groupable()
.Sortable()
.Selectable()
.Scrollable(s => s.Height("auto"))
.DataSource(ds => ds
.Ajax()
.Batch(true)
.ServerOperation(false)
.Events(events => events.Error("error_handler"))
.PageSize(20)
.Model(model =>
{
model.Id(a => a.Id);
})
.Read(read => read.Action("Read", "Users"))
.Update(update => update.Action("Update", "Users"))
)
.Events(events => events.Save("SaveChanges"))
)
<script>
function SaveChanges() {
setTimeout(function() {
$("#GridName").data("kendoGrid").dataSource.sync();
});
</script>
2- Controller
public ActionResult Update([DataSourceRequest] DataSourceRequest request, IEnumerable<User> models)
{
if (models != null && ModelState.IsValid)
{
if (models.Any())
{
foreach (var item in models)
{
Update(item); // Find item in database, modify the properties of the object & save change in database
}
}
}
return Json(models.ToDataSourceResult(request, ModelState));
}
I am building an MVC, Entities application with KendoGrids.
I have build this kendoGrid
#(Html.Kendo().Grid<ModelApp.Models.Tickets>()
.Name("ticketgrid")
.Columns(columns =>
{
columns.Bound(p => p.TicketID).Title("ID");
columns.ForeignKey(p => p.CustomerID, (System.Collections.IEnumerable)ViewData["customers"], "CustomerID", "CustomerName").Title("Customer");
columns.ForeignKey(p => p.AreaOfBusinessID, (System.Collections.IEnumerable)ViewData["areaofbusinesses"], "AreaOfBusinessID", "AreaOfBusiness1").Title("AreaOfBusiness");
columns.Bound(p => p.OccurredOn).Title("Occured").Format("{0:yyyy-MM-dd}");
columns.ForeignKey(p => p.SeverityID, (System.Collections.IEnumerable)ViewData["severities"], "SeverityID", "Severity1").Title("Severity");
columns.ForeignKey(p => p.AssigneeID, (System.Collections.IEnumerable)ViewData["assignees"], "AssigneeID", "AssigneeName").Title("Assignee");
columns.ForeignKey(p => p.TicketStatusID, (System.Collections.IEnumerable)ViewData["ticketstatuses"], "TicketStatusID", "TicketStatus1").Title("Status");
columns.Bound(p => p.UserID).Title("User");
columns.Bound(p => p.DateRegistered).Title("Registered").Format("{0:yyyy-MM-dd}");
})
.DataSource(dataSource =>
dataSource
.Ajax()
.Model(model => model.Id(p => p.TicketID))
.Read(read => read.Action("Index","Ticket"))
.Create(create => create.Action("Create", "Ticket"))
.Update(update => update.Action("Edit", "Ticket"))
//.Destroy(destroy => destroy.Action("Delete", "Ticket"))
)
.Pageable()
.Editable(editing => editing.Mode(GridEditMode.InCell))
.ToolBar(toolbar =>
{
toolbar.Create();
toolbar.Save();
})
.Navigatable()
.Selectable()
)
and I am facing 2 problems
1)The TicketID column is an identity column. When I select the Create button it fetches a zero. How can I make the Gid understand that it should not mess with this column and that the database will handle it?
Of course, no insert is being made anyway which takes me to the second question
2)The Edit does not post to database
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit([DataSourceRequest] DataSourceRequest request, IEnumerable<ModelApp.Models.Tickets> models)
{
if (models != null)
{
try
{
foreach (var updatedEntity in models)
{
var itemToUpdate = db.Tickets.Where(p => p.TicketID == updatedEntity.TicketID).FirstOrDefault();
if (itemToUpdate != null)
{
itemToUpdate.CustomerID = updatedEntity.CustomerID;
itemToUpdate.AreaOfBusinessID = updatedEntity.AreaOfBusinessID;
itemToUpdate.AssigneeID = updatedEntity.AssigneeID;
itemToUpdate.OccurredOn = updatedEntity.OccurredOn;
itemToUpdate.SeverityID = updatedEntity.SeverityID;
itemToUpdate.DateRegistered = updatedEntity.DateRegistered;
itemToUpdate.UserID = updatedEntity.UserID;
db.SaveChanges();
ModelState.Clear();
}
}
}
catch (Exception e)
{
db.add_exception_log(e.Message, "UPDATE RATES");
}
}
return Json(ModelState.ToDataSourceResult());
}
because models is null. Any clues why?
Thanx in advance
1) You should make the field non-editable inside of the Model configurator of the dataSource
model=>{
model.Fiedl(p=>p.TicketID).Editable(false);
}
2) You are not using batch editing to expect collection - change the signate to expect single record
public ActionResult Edit([DataSourceRequest] DataSourceRequest request, ModelApp.Models.Tickets model)
how to perform the edit and delete operations in grid
i have the following grid
<%=Html.Telerik().Grid(Model).Name("Grid").Columns(columns =>
{
columns.Bound(m => m.Keywords);
columns.Bound(m => m.Country).Title("Location");
columns.Bound(m => m.AreaID);
columns.Bound(m => m.JobSearchAgentID).Hidden(false);
}).DataBinding(databinding =>
{
databinding.Server().Select("Agentlist", "Grid", new
{
ajax = ViewData["ajax"]
});
databinding.Ajax().Select("Agentlist",
"Grid").Enabled((bool)ViewData["ajax"]);
})
.DataKeys(keys =>
{
keys.Add(m => m.JobSearchAgentID);
}
)
.Scrollable(scrolling => scrolling.Enabled((bool)ViewData["scrolling"]))
.Sortable(sorting => sorting.Enabled((bool)ViewData["sorting"]))
.Pageable(paging => paging.Enabled((bool)ViewData["paging"]))
.Filterable(filtering => filtering.Enabled((bool)ViewData["filtering"]))
.Groupable(grouping => grouping.Enabled((bool)ViewData["grouping"]))
.Footer((bool)ViewData["showFooter"])
%>
<%}%>
Everything you need about Telerik MVC Grid Control
http://demos.telerik.com/aspnet-mvc/grid/editingajax dead link
http://demos.telerik.com/aspnet-mvc/grid
Here's an example of a grid that allows add and edit within the grid:
<% Html.Telerik().Grid<ReportingPeriodGroupDto>()
.Name("ReportingPeriodGroupAdminGrid")
.DataKeys(keys => keys.Add(o => o.Id))
.Editable(editing => editing.Mode(GridEditMode.InLine))
.ToolBar(commands =>
{
commands.Insert();
})
.DataBinding(dataBinding => dataBinding.Ajax()
.Select("SelectReportingPeriodGroup", "Admin")
.Insert("InsertReportingPeriodGroup", "Admin")
.Update("UpdateReportingPeriodGroup", "Admin")
)
.Columns(columns =>
{
columns.Bound(o => o.ShortDescription).Width("10em").Width("8em");
columns.Bound(o => o.LongDescription).Width("20em");
columns.Command(commands => commands.Edit()).Title("Actions");
})
.Footer(false)
.Render();
%>
NOTE: You must add these Insert and Update methods to your controller
[AcceptVerbs(HttpVerbs.Post)]
[GridAction(GridName = "ReportingPeriodGroupAdminGrid")]
public ActionResult InsertReportingPeriodGroup()
{
ReportingPeriodGroupDto reportingPeriodGroupDto = new ReportingPeriodGroupDto();
TryUpdateModel(reportingPeriodGroupDto);
if (ModelState.IsValid)
{
reportingPeriodGroupDto.CreatedBy = UserId;
reportingPeriodGroupDto.CreatedDate = DateTime.Now.ToString();
ITransformer transformer = ServiceFinder.Instance.ServiceFactory.RedPortalTransformerFactory.GetTransformer(reportingPeriodGroupDto.GetType());
ReportingPeriodGroup parent = (ReportingPeriodGroup)transformer.Transform(reportingPeriodGroupDto);
RedPortalDbContext.ReportingPeriodGroups.Add(parent);
RedPortalDbContext.SaveChanges();
}
return SelectReportingPeriodGroup();
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction(GridName = "ReportingPeriodGroupAdminGrid")]
public ActionResult UpdateReportingPeriodGroup()
{
ReportingPeriodGroupDto reportingPeriodGroupDto = new ReportingPeriodGroupDto();
if (TryUpdateModel(reportingPeriodGroupDto))
{
reportingPeriodGroupDto.UpdatedBy = UserId;
reportingPeriodGroupDto.UpdatedDate = DateTime.Now.ToString();
ITransformer transformer = ServiceFinder.Instance.ServiceFactory.RedPortalTransformerFactory.GetTransformer(reportingPeriodGroupDto.GetType());
ReportingPeriodGroup parent = (ReportingPeriodGroup)transformer.Transform(reportingPeriodGroupDto);
RedPortalDbContext.ReportingPeriodGroups.Add(parent);
RedPortalDbContext.Entry(parent).State = EntityState.Modified;
RedPortalDbContext.SaveChanges();
}
return SelectReportingPeriodGroup();
}