Quantcast
Channel: DevExpress Support Center (Examples)
Viewing all 7205 articles
Browse latest View live

GridView - How to create a custom tooltip for cells to display long text

$
0
0

This example demonstrates how to create a custom tooltip for data cells using the PopupControl. The main idea is to assign a delegate method to the GridViewSettings.HtmlDataCellPrepared  property and handle the mouseover event to display a popup window.

[C#]
settings.HtmlDataCellPrepared=(s,e)=>{e.Cell.Attributes.Add("onmouseover",String.Format("OnMouseMove(this, event, '{0}');",e.KeyValue));};
[VB.NET]
settings.HtmlDataCellPrepared = Sub(s, e) e.Cell.Attributes.Add("onmouseover", String.Format("OnMouseMove(this, event, '{0}');", e.KeyValue)) EndSub
[JavaScript]
var oldKey = null;function OnMouseMove(element, event, key){if(typeof GridView.cpTooltipList[key] != "undefined"&& oldKey != key){ oldKey = key; PopupControl.ShowAtPos(event.clientX, event.clientY); ToolTipLabel.SetText("Item " + key + "<br/>" + GridView.cpTooltipList[key]);}}

The GridViewSettings.CustomJSProperties  property is used to pass data to the client side.

[C#]
settings.CustomJSProperties=(s,e)=>{MVCxGridViewgrid=sasMVCxGridView;intstartIndex=grid.VisibleStartIndex;intendIndex=grid.VisibleStartIndex+grid.SettingsPager.PageSize;varclientData=newDictionary<int,object>();for(inti=startIndex;i<endIndex;i++){varrowValues=grid.GetRowValues(i,newstring[]{"ID","Description"})asobject[];clientData.Add(Convert.ToInt32(rowValues[0]),rowValues[1]);}e.Properties.Add("cpTooltipList",clientData);};
[VB.NET]
settings.CustomJSProperties = Sub(s, e) Dim grid As MVCxGridView = TryCast(s, MVCxGridView) Dim startIndex AsInteger = grid.VisibleStartIndex Dim endIndex AsInteger = grid.VisibleStartIndex + grid.SettingsPager.PageSize Dim clientData = New Dictionary(OfInteger, Object)() For i AsInteger = startIndex To endIndex - 1 Dim rowValues = TryCast(grid.GetRowValues(i, NewString() {"ID", "Description"}), Object()) clientData.Add(Convert.ToInt32(rowValues(0)), rowValues(1)) Next i e.Properties.Add("cpTooltipList", clientData) EndSub

Files to look at:

HomeController.cs (VB: HomeController.vb)
SimpleModel.cs (VB: SimpleModel.vb)
GridViewPartial.cshtml
Index.cshtml

GridView - How to conditionally enable and disable the batch editing on the client side

$
0
0

This example demonstrates how to conditionally enable or disable the editing on the client side. You can find detailed steps by clicking below the "Show Implementation Details" link .

See also:
ASPxGridView - Batch Editing - How to conditionally enable and disable the editing on the client side

Description 1. Define a JavaScript variable that will control the edit state of the grid. This variable can be changed by your code or by other means. In this example, it is controlled by a check box:
[C#]
@Html.DevExpress().CheckBox(settings=>{settings.Name="AllowEditCB";settings.Properties.ClientSideEvents.CheckedChanged="OnAllowEditChanged";}).GetHtml()
[JavaScript]
function OnAllowEditChanged(s, e){ allowEdit = s.GetValue();}
2.  Handle the grid's client-side BatchEditStartEditing,  BatchEditRowDeletingBatchEditRowDeleting events to cancel the operation based on the value of the mentioned variable:
[C#]
settings.ClientSideEvents.BatchEditStartEditing="OnEditing";settings.ClientSideEvents.BatchEditRowDeleting="OnEditing";settings.ClientSideEvents.BatchEditRowInserting="OnEditing";
[JavaScript]
function OnEditing(s, e){ e.cancel = !allowEdit;}

Files to look at:

HomeController.cs (VB: HomeController.vb)
GridViewPartial.cshtml
Index.cshtml

GridView - EditForm template - How to enable Microsoft MVC validation

$
0
0

The example shows how to use Microsoft MVC validation (when the UnobtrusiveJavaScriptEnabled property is disabled in web.config). The main requirement is to create an Edit Form template with a form and editors. When a user needs to update a record, the following JavaScript should be invoked to process the Edit Form and check validation parameters:

[JavaScript]
function UpdateGridView(){ InitializeMVCValidationScript();var form = GetEditableForm();if(form.validationCallbacks[0](https://github.com/DevExpress-Examples/gridview-editform-template-how-to-enable-microsoft-mvc-validation-e3746/blob/14.1.3%2B/)) grid.UpdateEdit();}function InitializeMVCValidationScript(){var validationRulesScript = GetEditableForm().nextSibling;if(validationRulesScript && !validationRulesScript.executed){ validationRulesScript.executed = true; eval(validationRulesScript.text); Sys.Mvc.FormContext._Application_Load();}}function GetEditableForm(){return document.getElementById("frmProduct");}

How to enable unobtrusive validation for GridView using the EditForm template

Files to look at:

HomeController.cs (VB: HomeController.vb)
Product.cs (VB: Product.vb)
GridViewPartial.cshtml
Index.cshtml
ProductFormPartial.cshtml

GridView - BindToLINQ - How to export a large amount of filtered data with Reports

$
0
0

At present our MVCxGridView export mechanism has some limitations: it is impossible to export a lot of filtered data, because the mechanism requests all data from a database and then filters it. Thus, a request can be fulfilled, and the 'System.OutOfMemoryException' exception occurs. As a solution, request filtered data yourself and export it using the XtraReports Suite. This example demonstrates how you can do this using LINQ-to-SQL.

To pass the FilterExpression to a Controller's Action, obtain and save it to GridView CustomJSProperties in CustomJSProperties:

[C#]
settings.CustomJSProperties=(s,e)=>{MVCxGridViewgridView=(MVCxGridView)s;e.Properties["cpGridFilterExpression"]=gridView.FilterExpression;};
settings.CustomJSProperties = Sub(s, e)  
    Dim gridView = TryCast(s, MVCxGridView)  
    e.Properties("cpGridFilterExpression") = gridView.FilterExpression  
End Sub

When a user clicks the Export data, take the filter expression from GridView CustomJSProperties and add it to the collection of jQuery selector parameters.

[JavaScript]
function onClick(s, e){var actionParams = $("form").attr("action").split("?filterString="); actionParams[1] = encodeURIComponent(GridView.cpGridFilterExpression); $("form").attr("action", actionParams.join("?filterString="));}

The XtraReport class instance that's used in this Code Example is added as described in the Lesson 1 - Create a Static Report in ASP.NET MVC tutorial. The report controls are bound to data using the Embedded Fields (Mail Merge) feature.

You can learn more about approaches used in this example in the following resources:

How to: Create a Table Report
How to create a web based report at runtime
How to convert the CriteriaOperator to a lambda expression, so, the latter expression can be used in the IQueriable source

GridView Extension - Provide the capability to export large LINQ data

Files to look at:

HomeController.cs (VB: HomeController.vb)
XtraReport1.cs (VB: XtraReport1.vb)
LargeDatabaseDataProvider.cs (VB: LargeDatabaseDataProvider.vb)
GridViewPartial.cshtml (VB: GridViewPartial.vbhtml)
Index.cshtml (VB: Index.vbhtml)

GridView - Batch Editing - How to cancel editing or disable the editor conditionally

$
0
0

This example demonstrates how to cancel editing conditionally for the grid when batch editing is in use. It is possible to execute your logic either on the client or server side for a complex business model.
Then, handle the grid's client-side BatchEditStartEditing event to cancel the edit operation using the e.cancel property:

[JavaScript]
if(condition) e.cancel = true;

The custom server-side logic can be executed in the CustomJSProperties event handler:

[C#]
settings.CustomJSProperties+=(s,e)=>{varclientData=newDictionary<int,object>();vargrid=sasMVCxGridView;for(inti= 0;i<grid.VisibleRowCount;i++){varrowValues=grid.GetRowValues(i,newstring[]{"ID","ServerSideExample"})asobject[];varkey=Convert.ToInt32(rowValues[0]);if(key% 2 != 0)clientData.Add(key,"ServerSideExample");}e.Properties["cp_cellsToDisable"]=clientData;};

UPDATED:

Starting with v18.1, editors provide the client-side SetReadOnly method. To disable an editor conditionally, use the following code:

[JavaScript]
if(e.focusedColumn.fieldName == "ClientSideReadOnly"){ editor = s.GetEditor(e.focusedColumn.fieldName); editor.SetReadOnly(!condition);}

See Also:
ASPxGridView - Batch Editing - How to cancel editing or disable the editor conditionally

Files to look at:

HomeController.cs (VB: HomeController.vb)
GridViewPartial.cshtml
Index.cshtml

GridView - How to implement optimistic concurrency for the update/delete operations

$
0
0

This example illustrates how to realize optimistic concurrency when Binding to Data via Entity Framework (Code First). Note that Entity Framework includes the corresponding functionality out-of-the-box. You just need to define the following field in your data model:

[C#]
[Timestamp]publicByte[]RowVersion{get;set;}

Check the corresponding section in the Code First Data Annotations to learn more on this subject. Once you define this field, entity framework will automatically perform concurrency checks when saving data to the database. The DbUpdateConcurrencyException will be thrown in case of concurrency conflict.

This scenario is quite easy to implement in stateful environments like WinForms. But in the case of a stateless ASP.NET MVC environment, you need some additional logic over the default Entity Framework's logic to keep the current RowVersion value for the specific object between postbacks. In a regular MVC project, it is possible to use a hidden field for this purpose (e.g., see Handling Concurrency with the Entity Framework in an ASP.NET MVC Application (7 of 10)). In case of our MVC extensions you can use the approach illustrated in the How to: Access Server Data on the Client Side document to pass RowVersion-related data on the client side:

[C#]
settings.CustomJSProperties=(s,e)=>{MVCxGridViewgridView=(MVCxGridView)s;vardictionary=newSystem.Collections.Generic.Dictionary<object,string>();for(inti= 0;i<gridView.SettingsPager.PageSize;i++){varvisibleIndex=i+gridView.VisibleStartIndex;if(visibleIndex>=gridView.VisibleRowCount)break;object[]rowValues=(object[])gridView.GetRowValues(visibleIndex,gridView.KeyFieldName,"RowVersion");dictionary[rowValues[0].ToString()]=Convert.ToBase64String((byte[])rowValues[1]);}e.Properties["cpRowVersions"]=newSystem.Web.Script.Serialization.JavaScriptSerializer().Serialize(dictionary);if(ViewData["EditError"]!=null)e.Properties["cpEditError"]=ViewData["EditError"];};

After that, pass this data back to the corresponding Update/Delete controller's action method on the server side by using the approach from the Passing Values to Controller Action Through Callbacks document:

[JavaScript]
function GridView_BeginCallback(s, e){ e.customArgs['RowVersions'] = s.cpRowVersions;}

On the server side, deserialize this data and pass the correct value to the RowVersion field of the currently updated/deleted object. Here is an example (for Update action):

[C#]
publicActionResultGridViewPartialUpdate(Customercustomer){varmodel=db.Customers;customer.RowVersion=CalculateOldRowVersion(customer.Id);if(ModelState.IsValid){try{db.Entry(customer).State=System.Data.Entity.EntityState.Modified;db.SaveChanges();}catch(Exceptione){ViewData["EditError"]=e.Message;}}elseViewData["EditError"]="Please, correct all errors.";returnPartialView("GridViewPartial",db.Customers.ToList());}privatebyte[]CalculateOldRowVersion(intid){JavaScriptSerializerserializer=newJavaScriptSerializer();stringrowVersions=Request["RowVersions"];Dictionary<object,string>dictionary=(Dictionary<object,string>)serializer.Deserialize(rowVersions,typeof(Dictionary<object,string>));char[]rowVersion=dictionary[id.ToString()].ToCharArray();returnConvert.FromBase64CharArray(rowVersion, 0,rowVersion.Length);}

Files to look at:

HomeController.cs (VB: HomeController.vb)
Customer.cs (VB: Customer.vb)
GridViewPartial.cshtml
Index.cshtml

GridView - How to restore the expanded group rows state after a page is refreshed

GridView - How to specify an EditForm template only when adding a new row

$
0
0

This example illustrates how to specify a grid's EditForm template only when adding a new row and leave the default template when editing a row. Perform the following steps to accomplish this task:

1. Handle the MVCxClientGridView.BeginCallback event to determine which mode the grid will be in after a callback:

[JavaScript]
function OnBeginCallback(s, e){var isNewRowNow = s.IsNewRowEditing();var isSwitchToNewRow = (e.command == 'ADDNEWROW');var IsCancelEdit = (e.command == 'CANCELEDIT');var IsSwitchToEdit = (e.command == 'STARTEDIT'); var result = (isSwitchToNewRow * !IsCancelEdit + isNewRowNow) * !IsSwitchToEdit; e.customArgs['IsNewRow'] = Boolean(result);}

2. Process the received value in the controller and pass it to the view using ViewBag:

[C#]
[HttpPost,ValidateInput(false)]publicActionResultGridViewEditingPartial(boolIsNewRow){if(IsNewRow) ViewBag.IsNewRow=true;returnPartialView(list.GetPersons());}[HttpPost,ValidateInput(false)]publicActionResultEditingAddNew([ModelBinder(typeof(DevExpressEditorsBinder))]Personperson){ViewBag.IsNewRow=true;...}
3. After that, you can create a template based on the ViewBag value:
[C#]
if(ViewBag.IsNewRow!=null)   if(ViewBag.IsNewRow==true)       settings.SetEditFormTemplateContent(c=>       {           ViewContext.Writer.Write("EditForm Template Content");       });

Files to look at:

HomeController.cs (VB: HomeController.vb)
Person.cs (VB: Person.vb)
PersonsList.cs (VB: PersonsList.vb)
GridViewEditingPartial.cshtml
Index.cshtml

GridView - How to update total summaries on the client side in Batch Edit mode

$
0
0

Starting with v18.2 we support callbacks and keep the changes safe while a user navigates via pages, filters and sorts the grid data. If you use this version and above, please copy the 18.2.3+ branch as approaches to update summaries differ in new versions and old ones.

This example demonstrates how to update total summaries on the client side when GridView is in Batch Edit mode.

You can find detailed steps by clicking below the "Show Implementation Details" link .

See Also:
GridView - Batch Edit - How to calculate values on the fly
GridView - Batch Edit - How to calculate unbound column and total summary values on the fly

ASP.NET Web Forms Example:ASPxGridView - How to update total summaries on the client side in Batch Edit mode

Description

Starting with v16.1, it's possible to handle the ASPxClientGridView.BatchEditRowDeleting  and ASPxClientGridView.BatchEditChangesCanceling events to avoid using custom command buttons. (see step.3)

To implement the required task, perform the following steps:

1. Add a total summary item for a required column. The Tag property is used to find this summary item and get its value:

[C#]
settings.Columns.Add(column=>{column.FieldName="C2";column.ColumnType=MVCxGridViewColumnType.SpinEdit;ASPxSummaryItemsummaryItem=newASPxSummaryItem(column.FieldName,DevExpress.Data.SummaryItemType.Sum);summaryItem.Tag=column.FieldName+"_Sum";summaryItem.DisplayFormat="{0}";settings.TotalSummary.Add(summaryItem);});

 2. Replace the summary item with a custom Footer template:

[C#]
column.SetFooterTemplateContent(c=>{Html.DevExpress().Label(lbSettings=>{stringfieldName=(c.ColumnasGridViewDataColumn).FieldName;lbSettings.Name="labelSum";lbSettings.Properties.EnableClientSideAPI=true;ASPxSummaryItemsummaryItem1=c.Grid.TotalSummary.First(i=>i.Tag==(fieldName+"_Sum"));lbSettings.Text=c.Grid.GetTotalSummaryValue(summaryItem1).ToString();}).Render();});

 3.   Handle the ASPxClientGridView.BatchEditRowDeleting , ASPxClientGridView.BatchEditEndEditing ,  ASPxClientGridView.BatchEditChangesCanceling events to recalculate summary.

[JavaScript]
function OnBatchEditEndEditing(s, e){ CalculateSummary(s, e.rowValues, e.visibleIndex, false);}function CalculateSummary(grid, rowValues, visibleIndex, isDeleting){var originalValue = grid.batchEditApi.GetCellValue(visibleIndex, "C2");var newValue = rowValues[(grid.GetColumnByField("C2").index)].value;var dif = isDeleting ? -newValue : newValue - originalValue; labelSum.SetValue((parseFloat(labelSum.GetValue()) + dif).toFixed(1));}function OnBatchEditRowDeleting(s, e){ CalculateSummary(s, e.rowValues, e.visibleIndex, true);}function OnChangesCanceling(s, e){if(s.batchEditApi.HasChanges()) setTimeout(function(){ s.Refresh();}, 0);}

Files to look at:

HomeController.cs (VB: HomeController.vb)
Model.cs (VB: Model.vb)
_GridViewPartial.cshtml
Index.cshtml

GridView - How to upload an Excel file via UploadControl and show its data in a grid

$
0
0

Note

In version 19.2, we renamed our Range interface to CellRange - see the following BC for details: The DevExpress.Spreadsheet.Range interface has been renamed to DevExpress.Spreadsheet.CellRange.

This example shows how to load an Excel file from your computer to the server using MVCxUploadControl and then display its data in MVCxGridView.
Steps to implement this task are the following:

1. Implement the Helper class that returns the DataTable object based on your Excel file.
2. Implement the HomeControllerUploadControlSettings class that contains the FileUploadComplete static method to save the uploaded file itself and its path to the resultFilePath  variable. Also, in this class, implement the UploadValidationSettings property that returns UploadControl validation settings.
3. Map UploadControl's CallbackRouteValues property to the UploadControlUpload action. In this action, call the UploadControlExtension.GetUploadedFiles(UploadControlSettings,EventHandler method to pass UploadControl validation settings and invoke your FileUploadComplete method.
4. In the GridViewPartial action, get the DataTable object using the helper class and pass this table as a model to your _GridViewPartial.

Note:

The DevExpress.Docs assembly is used in this example. So, the Document Server subscription license is required to implement the demonstrated approach.

See also:
How to load an excel file to the server using ASPxUploadControl and display its data in ASPxGridView

Files to look at:

HomeController.cs (VB: HomeController.vb)
HelperClass.cs (VB: HelperClass.vb)
_GridViewPartial.cshtml
Index.cshtml

How to bind an ASP.NET MVC GridView extension to a table with an unknown schema using Custom Data Binding and XPO

$
0
0

Disclaimer:
This example demonstrates an edge-case scenario and uses XPO in an uncommon way. Refer to the following articles for XPO best practices:
How to use XPO in an ASP.NET (Web) application
How to bind editors to XPO objects in an ASP.NET MVC application

Targets:
The approach demonstrated in this example can be used when you need to take advantage of the partial data loading feature, but cannot use statically declared business models mapped to the database. This approach can be used to support adding/removing database columns without modifying the application code, to implement a generic View consuming data from an arbitrary table (or even database) selected by the user, or to implement a SaaS application.

Prerequisites:
This example is based on the following technologies:

1. eXpress Persistent Objects (aka XPO) are used as a data access layer. Refer to the tutorials in our online documentation to get started with XPO: Getting Started.
2. XPO supports dynamic mapping to the database tables without declaring any classes. Refer to this Knowledge Base article to learn more about this functionality: How to create persistent metadata on the fly and load data from an arbitrary table.
3. Our GridView component for ASP.NET MVC platform has an API that allows you to populate a grid with data manually taking into account the current grid state (filtering, sorting, grouping) - Custom Data Binding.
4. XPO provides components that can be used to load objects without knowing their types at compile time (XPCollection) or building complex queries with grouping, filtering, sorting and data aggregation (XPView).

Refer to our online documentation to understand concepts used in this example.

Implementation details:

1. This example extends a standard approach of connecting an ASP.NET application to an XPO data store described in this article: How to use XPO in an ASP.NET (Web) application. In this scenario, the persistent classes schema can be changed at run time. To address this requirement, it is necessary to create a separate Data Access Layer for each user, instead of sharing a single ThreadSafeDataLayer instance between all users as it recommended to do in regular scenarios. Refer to the XPO\XpoHelper.cs(vb) file for implementation details.
2. To handle the concurrent access to a data store, this example uses the DataStorePool component. XPO automatically creates DataStorePool when the connection string contains the special parameter. The XpoDefault.GetConnectionPoolString method is used to prepare such connection string.
3. The GetNewSession and GetNewUnitOfWork methods implemented in the extended XpoHelper class accept an XPDictionary instance as a last parameter. XPDictionary provides metadata information used to map persistent objects to database tables. In the example, the XPDictionary instance is prepared in the XPO\DatabaseSchemaHelper.cs(vb) file. This implementation is intended for demonstration purposes only. In real projects, it should be replaced with a custom implementation integrated with the application architecture and business requirements.
4. The XPO\XpoBindingHandlers.cs(vb) file contains a universal class that can be used in real projects without modifications. It provides the implementation of typed method delegates required to calling to a grid view model's GridViewModel.ProcessCustomBinding method. The usage is demonstrated in the Controllers\OrdersController.cs(vb) file.

How to use:

To add this functionality to an existing ASP.NET MVC project, do the following:
1. Copy the XPO\XpoHelper.cs(vb) file to your project. If the project already contains a similar helper class copied from the K18061 article, you can replace it or use both the implementations together.
2. Add required connection strings to your Web.config file. Refer to the Microsoft documentation to learn more about the configuration section: Creating a Connection String and Working with SQL Server LocalDB, SQL Server Connection Strings for ASP.NET Web Applications. If the application uses a database other than MS SQL Server, it is necessary to add a special parameter to a connection string. Refer to the following article for details: How to create a correct connection string for XPO providers.
3. Copy the XPO\XpoBindingHandlers.cs(vb) file to your project.
4. Using examples provided in the XPO\DatabaseSchemaHelper.cs(vb) file and the K18482 article, implement a helper class that builds metadata to map persistent objects to specific tables according to your business requirements.

Use the XpoBindingHandler class in your Controllers the same way as it is demonstrated in the Controllers\OrdersController.cs(vb) file. This class is independent from other parts of the project and can be re-used without modifications.

Files to look at:

OrdersController.cs (VB: OrdersController.vb)
DatabaseSchemaHelper.cs (VB: DatabaseSchemaHelper.vb)
XpoBindingHandlers.cs (VB: XpoBindingHandlers.vb)
XpoHelper.cs (VB: XpoHelper.vb)

GridView - How to validate a model field based on another field's value

$
0
0

This example demonstrates how to implement custom model validation for one field based on a another field's value.
To accomplish this task, create a ValidationAttribute class descendant and override the IsValid method.
You can learn more about this in the How to: Customize Data Field Validation in the Data Model Using Custom Attributes article.

Files to look at:

CustomAttribute.cs (VB: CustomAttribute.vb)
HomeController.cs (VB: HomeController.vb)
MyModel.cs (VB: MyModel.vb)
_GridViewPartial.cshtml
Index.cshtml

How to bind GridView extension to a Model filtered by some value when using BindToLINQ

$
0
0

When using server mode, all data operations are processed at the database level rather than at the GridView level. So, it is impossible to implement custom filtering when using the BindToLINQ method. At the same time, it is possible to assign a filter criteria to the GridView's QueryableSource before the GridView sends a request to a database. For this, do the following:

- In the BindToLINQ function, add the "where" statement to filter a grid;

- When a user submits a form or performs a callback to GridView, you can fill a Session by a value from Request.Params and use this Session in the "where" statement.

Here is a small example of using the BindToLINQ method:

[C#]
@Html.DevExpress().GridView(settings=>{settings.Name="grid";...}).BindToLINQ(string.Empty,string.Empty,(s,e)=>{e.QueryableSource=LargeDatabaseDataProvider.GetProductsByFilter(ViewData["CmbValue"]);e.KeyExpression="ProductID";}).GetHtml()
[VB.NET]
@Html.DevExpress().GridView( _ Sub(settings) settings.Name = "grid" ... EndSub).BindToLINQ("", "", (Function(s, e) e.QueryableSource = VB.LargeDatabaseDataProvider.GetProductsByFilter(ViewData("CmbValue")) e.KeyExpression = "ProductID"EndFunction)).GetHtml()

See also:
Walkthrough: Installing the AdventureWorks Database

Files to look at:

HomeController.cs (VB: HomeController.vb)
Model.cs (VB: Model.vb)
GridViewPartial.cshtml
Index.cshtml

GridView - How to track changes made with an unbound CheckBox in the DataItemTemplate

$
0
0

This example illustrates how to:
- Define a custom editor (for example, the CheckBox) inside the column's DateItemTemplate (via the GridViewSettings.SetDataItemTemplateContent method);
- Specify the CheckBox.Name property based on the corresponding DataRow's keyValue (this operation requires specifying the GridViewSettings.KeyFieldName property);
- Subscribe the client-side ASPxClientCheckBox.CheckedChanged event;
- Store the CheckBox's state via a custom JavaScript object like a dictionary/key value pairs (the CheckBox.Name - Checked State)

An end-user is able to select/deselect the CheckBoxes displayed within the column.
When the user tries to perform any GridView's callback (sorting, paging, etc.), the stored key value pairs collection is serialized via the "toJSON" plugin (available with the jquery-json library). The serialized object is passed to a Controller as custom argument according to the "Passing Values to Controller Action Through Callbacks" technique.
The passed serialized object is de-serialized on the Controller side and passed to the View object to restore an unbound CheckBox state.

View:

[JavaScript]
<script type="text/javascript"> var DXHiddenObject = {};function OnBeginCallback(s, e){ e.customArgs["items"] = $.toJSON(DXHiddenObject);}function OnCheckedChanged(s, e){if(s.GetChecked()) DXHiddenObject[s.name] = true;elsedelete DXHiddenObject[s.name];}</script>

PartialView:

C#:

[C#]
@Html.DevExpress().GridView(settings=>{settings.Name="gvTypedListDataBinding";settings.CallbackRouteValues=new{Controller="Home",Action="TypedListDataBindingPartial"};settings.KeyFieldName="ID";...settings.Columns.Add(column=>{column.SetDataItemTemplateContent(c=>{Html.DevExpress().CheckBox(checkboxSettings=>{checkboxSettings.Name="cb_"+c.KeyValue.ToString();checkboxSettings.Properties.ClientSideEvents.CheckedChanged="OnCheckedChanged";if(ViewData["items"]!=null){Dictionary<string,bool>items=(Dictionary<string,bool>)ViewData["items"];checkboxSettings.Checked=items.ContainsKey(checkboxSettings.Name)&&(bool)items[checkboxSettings.Name];}}).Render();});});settings.ClientSideEvents.BeginCallback="OnBeginCallback";}).Bind(Model).GetHtml()

VB.NET:

[VB.NET]
@Html.DevExpress().GridView( _ Sub(settings) settings.Name = "gvTypedListDataBinding" settings.CallbackRouteValues = NewWith {Key .Controller = "Home", Key .Action = "TypedListDataBindingPartial"} settings.KeyFieldName = "ID" ... settings.Columns.Add( _ Sub(column) column.SetDataItemTemplateContent( _ Sub(c) Html.DevExpress().CheckBox( _ Sub(checkboxSettings) checkboxSettings.Name = "cb_" + c.KeyValue.ToString() checkboxSettings.Properties.ClientSideEvents.CheckedChanged = "OnCheckedChanged"If (ViewData("items") IsNot Nothing) ThenDim items As Dictionary(OfString, Boolean) = CType(ViewData("items"), Dictionary(OfString, Boolean)) checkboxSettings.Checked = items.ContainsKey(checkboxSettings.Name) AndAlsoCBool(items(checkboxSettings.Name)) EndIfEndSub).Render() EndSub) EndSub) settings.ClientSideEvents.BeginCallback = "OnBeginCallback"EndSub).Bind(Model).GetHtml()

Controller:

[C#]
publicclassHomeController:Controller{publicActionResultIndex(){if(Session["TypedListModel"]==null)Session["TypedListModel"]=InMemoryModel.GetTypedListModel();returnView(Session["TypedListModel"]);}publicActionResultTypedListDataBindingPartial(){ViewData["items"]=GetSerializedObject(Request["items"]);returnPartialView(Session["TypedListModel"]);}privateDictionary<string,bool>GetSerializedObject(stringinputString){if(string.IsNullOrEmpty(inputString))returnnull;Dictionary<string,bool>items=null;try{items=newJavaScriptSerializer().Deserialize<Dictionary<string,bool>>(inputString);}catch{ViewData["ErrorMessage"]="Invalid Input JSON String";}returnitems;}}

VB.NET

[VB.NET]
PublicClass HomeController Inherits Controller PublicFunction Index() As ActionResult If Session("TypedListModel") IsNothingThen Session("TypedListModel") = InMemoryModel.GetTypedListModel() EndIfReturn View(Session("TypedListModel")) EndFunctionPublicFunction TypedListDataBindingPartial() As ActionResult ViewData("items") = GetSerializedObject(Request("items")) Return PartialView(Session("TypedListModel")) EndFunctionPrivateFunction GetSerializedObject(ByVal inputString AsString) As Dictionary(OfString, Boolean) IfString.IsNullOrEmpty(inputString) ThenReturnNothingEndIfDim items As Dictionary(OfString, Boolean) = NothingTry items = New JavaScriptSerializer().Deserialize(Of Dictionary(OfString, Boolean))(inputString) Catch ViewData("ErrorMessage") = "Invalid Input JSON String"EndTryReturn items EndFunctionEndClass

Files to look at:

HomeController.cs (VB: HomeController.vb)
Index.cshtml
TypedListDataBindingPartial.cshtml

How to use GridView in Batch Edit mode in another grid Edit Form

$
0
0

This example demonstrates how to edit a detail grid with Batch Edit mode enabled in the master grid edit form. The main point is that it is impossible to update both grids simultaneously. So, we need to send two consequent callbacks to update the detail and master grids:

[JavaScript]
function onUpdateButton (s, e){if(detail.batchEditApi.HasChanges()) detail.UpdateEdit();else master.UpdateEdit();}function onDetailEndCallback(s, e){ master.UpdateEdit();}

This code describes the basic principle, while the example shows a more complex and thorough implementation. Also, this approach requires additional actions when a new row is created in the master grid. As the detail grid is saved before the master grid, when a new row is created, the detail grid doesn't have the master key which is used to save the details. In this case, you will have to save the detail grid data to a temporary field and then write changes when the master row is created.

Files to look at:

HomeController.cs (VB: HomeController.vb)
DataContext.cs (VB: DataContext.vb)
GridViewOrderItems.cshtml
GridViewOrders.cshtml
Index.cshtml
_Layout.cshtml

How to provide custom summary texts within GridView

How to implement the multi-row editing feature in the GridView

$
0
0

UPDATED:

Starting with version 13.2, the GridView control offers the basic "Batch Editing Mode" functionality that allows accomplishing a similar task with less effort and does not require so much extra code. See the ASP.NET WebForms & MVC: GridView Batch Edit blog post to learn more about this new functionality.
Starting with version 14.1, the GridView control offers advanced "Batch Editing Mode" programming options.

You can find a standalone DB-independent solution in our Code Examples base at:
GridView - A simple Batch Editing implementation

If you have version v14.1+ available, consider using the built-in functionality instead of the approach detailed below.
If you need further assistance with this functionality, please create a new ticket in our Support Center.

This example demonstrates how to implement the multi-row editing feature using the GridView extension. The main idea is to save changed values in the JavaScript dictionary and pass this dictionary to the required action. It is necessary to use a custom ModelBinder in the action to convert passed data to the required dictionary object.

See also:
How to perform GridView instant updating using different editors in the DataItem template
GridView - How to implement batch update using the Ajax request
How to implement the multi-row editing feature in the ASPxGridView
IModelBinder Interface
ASP.NET MVC2 - Custom Model Binder Examples
jQuery.ajax()

Web Forms:
How to implement the multi-row editing feature in the ASPxGridView

DockPanel - How to create DockPanels dynamically and persist their state to cookies

$
0
0

This example illustrates how to add DockPanel to the view dynamically and restore their layout from cookies when view page is reloaded. We are using the approach from the How to use the jQuery.ajax function with DevExpress MVC Extensions code example to generate a new DockPanel on the server side and add its resulting HTML to the view page:

[JavaScript]
$.ajax({ url: '@Url.Action("DockPanelPartial", "Home")', type: "POST", data: { index: count }, success: function(response){ $(response).appendTo('#ajaxDiv'); ASPxClientUtils.SetCookie("panelsCount", count + 1);}});

In addition, make a note of the code used to restore previously created DockPanels:

[C#]
<divid="ajaxDiv">@* Restore old panels: *@@if(Request.Cookies["panelsCount"]!=null){intpanelsCount=Convert.ToInt32(Request.Cookies["panelsCount"].Value);for(inti= 0;i<panelsCount;i++){Html.RenderAction("DockPanelPartial","Home",new{index=i});}}</div>

Files to look at:

HomeController.cs (VB: HomeController.vb)
DockPanelPartial.cshtml
Index.cshtml

PopupControl - How to implement a confirmation dialog

$
0
0

In this example, we consider the confirmation dialog as a simple popup with a message and Yes/No buttons.

For this task, you need to place a popup into Layout view and place the label and buttons there:

[C#]
@Html.DevExpress().PopupControl(settings=>{settings.SetContent(()=>{//label and buttons });}).GetHtml()

And write a simple JS function that will show this popup and assign the handler to the Yes button:

[JavaScript]
(function(){'use strict'; window.dxConfirm = function(text){if(text && text.length) ConfirmLabel.SetText(text); ConfirmYes.Click.ClearHandlers(); ConfirmYes.Click.AddHandler(Hide); ConfirmPopup.Show();return{ success: function(onSuccess){ ConfirmYes.Click.AddHandler(onSuccess);}};};function Hide(){ ConfirmPopup.Hide();}})();

Then, you will be able to use the dialog as follows:

[JavaScript]
dxConfirm("Do you want to show an alert?").success(function(){ alert("success");});

Here, the string parameter is the message that will be shown in the popup and the function passed to success  defines the action that will be performed after Yes is clicked.
If you pass an empty string, the default message will be shown. However, the success function is required as there is no point in using the dialog without it.

Files to look at:

dxConfirm.js
Index.cshtml
_Layout.cshtml
ConfirmPopup.cshtml

PopupControl - How to display the control after executing controller code

$
0
0

This example illustrates several approaches to display the PopupControl extension after performing server-side processing. In the simplest scenario we use the PopupControlSettingsBase.ShowOnPageLoad option to display the popup control initially. Note that we can pass any dynamic settings or content for the popup control through the ViewData dictionary. To show the popup control on the client side, we can call the ASPxClientPopupControlBase.Show() method. In addition we can use the ASPxClientPopupControlBase.SetContentHtml method to modify popup content on the client side.

Finally, there is a scenario when the popup control should be displayed after a callback of some other extension. Please review the T159638 - GridView - How to show a message after CRUD operations code example, where we have illustrated how this can be implemented.

See also:
How to make PopupControl stay open after submitting a form using Ajax.BeginForm

Files to look at:

HomeController.cs (VB: HomeController.vb)
AfterAsyncAjaxFormSubmit.cshtml
AfterJQueryAjax.cshtml
AfterSyncFormSubmit.cshtml
Index.cshtml
OnLoad.cshtml
Viewing all 7205 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>