my code is too long so sorry :)
#model IEnumerable<Osos11.Models.Customers>
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "gvEditing";
settings.KeyFieldName = "sno";
settings.CallbackRouteValues = new { Controller = "Customer", Action = "EditingPartial" };
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.Columns.Add(column =>
{
column.Caption = "#";
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("Edit", "EditingEdit", new { sno = DataBinder.Eval(c.DataItem, "sno") }) + " " +
Html.ActionLink("Delete", "EditingDelete", new { sno = DataBinder.Eval(c.DataItem, "sno") },
new { onclick = "return confirm('Do you really want to delete this record?')" })
);
});
column.SetHeaderTemplateContent(c =>
{
ViewContext.Writer.Write(
Html.ActionLink("New", "EditingEdit", new { sno = -1 }).ToHtmlString()
);
});
column.Settings.AllowDragDrop = DefaultBoolean.False;
column.Settings.AllowSort = DefaultBoolean.False;
column.Width = 70;
});
settings.Columns.Add("Name");
//settings.Columns.Add(column =>
//{
// column.FieldName = "CategoryID";
// column.Caption = "Category";
// column.ColumnType = MVCxGridViewColumnType.ComboBox;
// var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
// comboBoxProperties.DataSource = NorthwindDataProvider.GetCategories();
// comboBoxProperties.TextField = "CategoryName";
// comboBoxProperties.ValueField = "CategoryID";
// comboBoxProperties.ValueType = typeof(int);
//});
settings.Columns.Add("CustomerNumber");
//settings.Columns.Add("UnitPrice").PropertiesEdit.DisplayFormatString = "c";
//settings.Columns.Add("UnitsInStock");
//settings.Columns.Add("Discontinued", MVCxGridViewColumnType.CheckBox);
settings.ClientLayout = (s, e) =>
{
if (e.LayoutMode == ClientLayoutMode.Loading)
{
if (Session["GridState"] != null)
e.LayoutData = (string)Session["GridState"];
}
else
Session["GridState"] = e.LayoutData;
};
settings.PreRender = (s, e) =>
{
if (ViewData["VisibleID"] == null) return;
ASPxGridView grid = (ASPxGridView)s;
grid.MakeRowVisible(ViewData["VisibleID"]);
};
}).Bind(Model).GetHtml()
I got this error
Compiler Error Message: CS1660: Cannot convert lambda expression to type 'DevExpress.Web.Mvc.GridViewSettings' because it is not a delegate type
It seems that this issue is caused by the fact that any expression in the GridView's definition is not valid.
As a result, the entire GridView's definition (lambda expression) cannot be recognized by the View Engine.
Related
I have a problem with the system for ordering products.
Scenario:
Two separate browsers
Two separate accounts (after logging in a separate session id)
when clicked, grouped, and enabled in the connect string MultipleActiveResultSets = true.
Users click at the same time (each has different filters set, grouping), but when the second user clicks on, the user gets the result of the first user query (different parameters)
Update
[C#]
PartialViewResult AdvancedCustomBindingCore(GridViewModel viewModel)
{
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKar(_Session));///////////////////-------------------ustawiamy do modelu zrodlo danych .....
if (Session["fulltextsearch"] == null)
{
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKar(_Session));
Session["fulltextsearch"] = null;
}
else
{
GridViewCustomBindingHandlers.SetModel(iMagoDataProvider.Get_f_MgKarFullTextSearch(_Session));
}
viewModel.ProcessCustomBinding(
GridViewCustomBindingHandlers.GetDataRowCountAdvanced,
GridViewCustomBindingHandlers.GetDataAdvanced,
GridViewCustomBindingHandlers.GetSummaryValuesAdvanced,
GridViewCustomBindingHandlers.GetGroupingInfoAdvanced,
GridViewCustomBindingHandlers.GetUniqueHeaderFilterValuesAdvanced
);
return PartialView("GridViewMgKarPartial", viewModel);
}
static GridViewModel CreateGridViewModelWithSummary()
{
var viewModel = new GridViewModel();///////////////////-------------------ustawiamy kolumny ze zrodla danych.....
viewModel.KeyFieldName = "SymKar;LogoP;JM;SymWL";
viewModel.Columns.Add("SymKar");
viewModel.Columns.Add("SymKarObcy");
viewModel.Columns.Add("OpiKar");
viewModel.Columns.Add("L_OpiKar_EN");
viewModel.Columns.Add("JM");
//////////////Jezeli ma byc niewidoczna to w cshtml tez sie musi zgadzac....czyli nie dodajemy
viewModel.Columns.Add("CenaNetto");
//////////////Jezeli ma byc niewidoczna to w cshtml tez sie musi zgadzac....czyli nie dodajemy
viewModel.Columns.Add("IloscPAL");
viewModel.Columns.Add("StanDys");
viewModel.Columns.Add("GruKar");
viewModel.Columns.Add("Waga");
viewModel.Columns.Add("LogoP");
viewModel.Columns.Add("RodzajHandlowy");
viewModel.Pager.PageSize = 20;
//viewModel.TotalSummary.Add(new GridViewSummaryItemState() { FieldName = "Size", SummaryType = SummaryItemType.Sum });
//viewModel.TotalSummary.Add(new GridViewSummaryItemState() { FieldName = "Subject", SummaryType = SummaryItemType.Count });
//viewModel.GroupSummary.Add(new GridViewSummaryItemState() { FieldName = string.Empty, SummaryType = SummaryItemType.Count });
return viewModel;
}
#endregion CustomBindingRoute_Settings
#region CustomBindingRoute_General
public ActionResult GridViewMgKarPartial(string selectedValues)//------------------------------------------------Ustawiamy nazwe dla View ktory powstal...........
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
Session[_SessionSelected] = selectedValues;
GridViewModel viewModel = GridViewExtension.GetViewModel(str_GridViewName);
if (viewModel == null)
viewModel = CreateGridViewModelWithSummary();
string _FilterExpression = "";
int FILTER_UserID = usr.users_ID;
if (Session["myGridStatefiltrKM"] != null)
{
var userFiltersList = iMagoDataProvider.wusr_f_GetUserFiters(FILTER_UserID, "GridView_mpid_" + menu_pozycje_ID).Where(x => x.wusr_GrdFiltMenForSessionidId == Convert.ToInt32(Session["myGridStatefiltrKM"])).ToList().OrderByDescending(m => m.DomyslnyFiltr).ThenByDescending(m => m.DateCreated);
foreach (var item in userFiltersList)
{
_FilterExpression = item.FilterExpression.ToString();
}
}
if (_FilterExpression != "")
viewModel.FilterExpression = _FilterExpression;//"StartsWith([SymKar], 'aa')";
return AdvancedCustomBindingCore(viewModel);
}
// Paging
public ActionResult AdvancedCustomBindingPagingAction(GridViewPagerState pager)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyPagingState(pager);
string _FilterExpression = "";
try
{
db.wusr_p_GetGridFilterMenuForUsers(_Session, menu_pozycje_ID, str_GridViewName, ref _FilterExpression);//Pamietaj o wpisaniu prawidlowej nazwy dla grida(unikatowego w obrebie menu)
}
catch (Exception e)
{
return ExceptionHandle(e);
}
if (_FilterExpression != "")
{
viewModel.FilterExpression = _FilterExpression;//"StartsWith([SymKar], 'aa')";
}
if (Session["fulltextsearch"] == null)
{
//var model = iMagoDataProvider.Get_f_ListaZgloszen(userSessionid, 1);
Session["fulltextsearch"] = null;
return AdvancedCustomBindingCore(viewModel);
// return PartialView("Lista", model);
}
else
{
if (Session["filtr"] != null)
{
viewModel.FilterExpression = Session["filtr"].ToString();
}
var model = Session["fulltextsearch"];
return AdvancedCustomBindingCore(viewModel);
}
// return AdvancedCustomBindingCore(viewModel);
}
// Filtering
public ActionResult AdvancedCustomBindingFilteringAction(GridViewFilteringState filteringState)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyFilteringState(filteringState);
//Zapamietujemy filtry - na okres sessji ... pozniej odczytujemy ogolne tak by przy nowej sesji zawsze byly domyslne
int FILTER_UserID = usr.users_ID;
string _FilterExpression = "";
if (Session["myGridStatefiltrKM"] != null)
{
var userFiltersList = iMagoDataProvider.wusr_f_GetUserFiters(FILTER_UserID, "GridView_mpid_" + menu_pozycje_ID).Where(x => x.wusr_GrdFiltMenForSessionidId == Convert.ToInt32(Session["myGridStatefiltrKM"])).ToList().OrderByDescending(m => m.DomyslnyFiltr).ThenByDescending(m => m.DateCreated);
foreach (var item in userFiltersList)
{
_FilterExpression = item.FilterExpression.ToString();
}
}
return AdvancedCustomBindingCore(viewModel);
}
// Sorting
public ActionResult AdvancedCustomBindingSortingAction(GridViewColumnState column, bool reset)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplySortingState(column, reset);
return AdvancedCustomBindingCore(viewModel);
}
// Grouping
public ActionResult AdvancedCustomBindingGroupingAction(GridViewColumnState column)
{
int menu_pozycje_ID = System.Convert.ToInt32(Session[SessionEl.SESSION_MENU_ACT]);
UserDBModel usr = (UserDBModel)Session[SessionEl.SESSION_USER];
long _Session = System.Convert.ToInt64(usr.UserSessionID);
try
{
SortedList<string, model_Uprawnienia> rights = db.getPrawa(_Session, menu_pozycje_ID); ViewBag.Rights = rights;
}
catch (Exception e)
{
return ExceptionHandle(e);
}
var viewModel = GridViewExtension.GetViewModel(str_GridViewName);
viewModel.ApplyGroupingState(column);
return AdvancedCustomBindingCore(viewModel);
}
Partial View
[HTML]
#{
SortedList<string, IMago.Models.model_Uprawnienia> rights = ViewBag.Rights;
}
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "GridView_mgKar";
settings.CallbackRouteValues = new { Controller = "KartotekaMaterialowa", Action = "GridViewMgKarPartial" };
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Filtr"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Filtering,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingFilteringAction" }
);
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Group"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Grouping,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingGroupingAction" }
);
settings.Width = System.Web.UI.WebControls.Unit.Percentage(100);
settings.KeyFieldName = "SymKar;LogoP;JM;SymWL";
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.SettingsBehavior.AllowSelectByRowClick = false;
settings.Settings.ShowFilterBar = GridViewStatusBarMode.Visible;
settings.Settings.ShowFooter = true;
settings.SettingsSearchPanel.Visible = false;
settings.Settings.ShowFilterRowMenuLikeItem = true;
settings.Settings.ShowHeaderFilterButton = true;
settings.EnableRowsCache = false;
settings.Styles.AlternatingRow.Enabled = DefaultBoolean.True;
settings.Styles.AlternatingRow.BackColor = System.Drawing.Color.White;
settings.Styles.Row.BackColor = System.Drawing.Color.WhiteSmoke;
settings.Styles.FocusedRow.CssClass = "EmptyFocusedRow";
settings.Styles.RowHotTrack.CssClass = "RowHover";
settings.Styles.Cell.Wrap = DefaultBoolean.False;
settings.Styles.Cell.Font.Size = FontUnit.Smaller;
settings.Styles.Header.Font.Size = FontUnit.XSmall;
settings.Styles.Header.Font.Bold = true;
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymKar"))
settings.Columns.Add(c =>
{
c.FieldName = "SymKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKar").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_Nag_Kol_pd_isstandard")) //Przy ZPW
settings.Columns.Add(column =>
{
column.FieldName = "pd_isstandard";
column.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolpd_isstandard").ToUpper();
column.Width = 20;
column.HeaderStyle.Wrap = DefaultBoolean.True;
column.ColumnType = MVCxGridViewColumnType.CheckBox;
column.ReadOnly = true;
//column.PropertiesEdit.DisplayFormatString = "c";
column.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymKarObcy"))
settings.Columns.Add(c =>
{
c.FieldName = "SymKarObcy";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKarObcy").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_OpiKar"))
settings.Columns.Add(c =>
{
c.FieldName = "OpiKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolOpikar").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_L_OpiKar_EN"))
settings.Columns.Add(c =>
{
c.FieldName = "L_OpiKar_EN";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolOpikarEn").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_JM"))
settings.Columns.Add(c =>
{
c.FieldName = "JM";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolJM").ToUpper();
c.Width = 50;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_CenaNetto"))
settings.Columns.Add(c =>
{
c.FieldName = "CenaNetto";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolCenaNetto").ToUpper();
c.PropertiesEdit.DisplayFormatString = PageHelper.N2_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_SymWL"))
settings.Columns.Add(c =>
{
c.FieldName = "SymWL";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymWL").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_IloscPAL"))
settings.Columns.Add(c =>
{
c.FieldName = "IloscPAL";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolIloscCalopaletowa").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N0_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_StanDys"))
settings.Columns.Add(c =>
{
c.FieldName = "StanDys";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolStanWolny").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N0_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_GruKar"))
settings.Columns.Add(c =>
{
c.FieldName = "GruKar";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolSymKarGrup").ToUpper();
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_Waga"))
settings.Columns.Add(c =>
{
c.FieldName = "Waga";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolWaga").ToUpper();
c.Width = 50;
c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format;
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_LogoP"))
settings.Columns.Add(c =>
{
c.FieldName = "LogoP";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolLogoP").ToUpper();
// c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Kol_RodzajHandlowy"))
settings.Columns.Add(c =>
{
c.FieldName = "RodzajHandlowy";
c.Settings.AutoFilterCondition = AutoFilterCondition.Contains;
c.Caption = IMago.Models.ResourcesModel.GetRes("TytulKolRodzajHandlowy").ToUpper();
// c.PropertiesEdit.DisplayFormatString = PageHelper.N3_Format
});
if (PageHelper.isVisible(rights, "GridView_mgKar_Grid_Oper_Sort"))
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Sorting,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingSortingAction" }
);
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Paging,
new { Controller = "KartotekaMaterialowa", Action = "AdvancedCustomBindingPagingAction" }
);
settings.EnableCallbackAnimation = false;
settings.CommandColumn.Visible = true;
settings.CommandColumn.ShowSelectCheckbox = true;
settings.CommandColumn.Width = Unit.Pixel(65);
settings.SettingsBehavior.ConfirmDelete = true;
settings.SettingsBehavior.AllowFocusedRow = true;
settings.ClientSideEvents.SelectionChanged = "OnSelectionChanged";
settings.ClientSideEvents.EndCallback = "OnEndCallback";
settings.CustomJSProperties = (sender, e) =>
{
e.Properties["cpFilterExpression"] = (sender as MVCxGridView).FilterExpression;
MVCxGridView g = sender as MVCxGridView;
Dictionary<int, object> dict = new Dictionary<int, object>();
int startIndex = g.PageIndex * g.SettingsPager.PageSize;
int endIndex = startIndex + g.SettingsPager.PageSize;
int kluczpomocny = 0;
for (int i = startIndex; i < endIndex; i++)
{
string klucz = g.GetRowValues(i, "SymKar") + "|" + g.GetRowValues(i, "LogoP") + "|" + g.GetRowValues(i, "JM") + "|" + g.GetRowValues(i, "SymWL");
dict[kluczpomocny] = klucz + "<|>" + g.GetRowValues(i, "LogoP") + "<|>" + g.GetRowValues(i, "JM") + "<|>" + g.GetRowValues(i, "SymWL") + "<|>" + g.GetRowValues(i, "CenaNetto")+"<|>"+ g.GetRowValues(i, "SymKar");
kluczpomocny++;
}
e.Properties["cpData"]=dict;
};
}).BindToCustomData(Model).GetHtml()
official reply from DevExpress:
"Thank you for the sample project and database backup. I was able to reproduce both issues on my side. I also analyzed how your data layer works when this behavior is reproducible and now I see what causes the issue: you are placing an IQueriable model instance in a static field which is shared among different requests.
As far as I understand, you used the code for the helper class from our Custom Data Binding (Advanced) demo. In this demo, the data source can't be different: a query is always executed on the non-parameterized Emails data set. That's why we put it in a static property.
In your case, the static Model property will not work correctly for multiple concurrent requests. On each request, you are changing an IQueriable instance to a user-specific parameterized query. Due to the fact that an IQueriable instance uses the lazy-loading feature, a query is only executed when the ToList method is invoked (it is done internally in the GridView extension code). That's why you may encounter a situation when the following scenario occurs: you set a model for Grid1 and start building a database query in the GetDataAdvanced method, but at that time, Grid2 set its own model. Thus, substituting the model (the parameterized query to a stored procedure) of the first SQL query built by Grid1.
To fix this issue, I suggest that you make the GridViewCustomBindingHandlers class non-static and create an instance of this class for each controller. This will resolve the issue with the same data for two different users. Make sure that the 'MultipleActiveResultSets' parameter in the connection string is set to 'True'. I demonstrated the implementation of this approach in the updated sample project in the attachment.
Regarding the code in our demo: I described why we implemented it in this way above. However, our implementation in the demo made you implement your own data layer incorrectly. As we try to show the best practices in our demos, the fact that our implementation caused confusion did not go unnoticed. I passed the information regarding your scenario to the team for discussion. This will help us implement better demos/examples in the future or update the existing ones."
I am working on user roles using Asp.net MVC. I am stuck while working on Admin section. I have mentioned one question above and the second question is similar which is Using the generic type 'System.Collections.Generic.List' requires 1 type arguments
Here is my code.
public ActionResult Index(string searchStringUserNameOrEmail, string currentFilter, int? page)
{
try
{
int intPage = 1;
int intPageSize = 5;
int intTotalPageCount = 0;
if (searchStringUserNameOrEmail != null)
{
intPage = 1;
}
else
{
if (currentFilter != null)
{
searchStringUserNameOrEmail = currentFilter;
intPage = page ?? 1;
}
else
{
searchStringUserNameOrEmail = "";
intPage = page ?? 1;
}
}
ViewBag.CurrentFilter = searchStringUserNameOrEmail;
List col_UserDTO = new List();
int intSkip = (intPage - 1) * intPageSize;
intTotalPageCount = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.Count();
var result = UserManager.Users
.Where(x => x.UserName.Contains(searchStringUserNameOrEmail))
.OrderBy(x => x.UserName)
.Skip(intSkip)
.Take(intPageSize)
.ToList();
foreach (var item in result)
{
ExpandedUserDTO objUserDTO = new ExpandedUserDTO();
objUserDTO.UserName = item.UserName;
objUserDTO.Email = item.Email;
objUserDTO.LockoutEndDateUtc = item.LockoutEndDateUtc;
col_UserDTO.Add(objUserDTO);
}
// Set the number of pages
// Error appears here
var _UserDTOAsIPagedList =
new StaticPagedList
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
return View(_UserDTOAsIPagedList);
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Error: " + ex);
List col_UserDTO = new List(); // Error appears here
return View(col_UserDTO.ToPagedList(1, 25));
}
}
#endregion
`
StaticPagedList is generic. You need to supply the type of collection(for col_UserDTO), in your case List:
var _UserDTOAsIPagedList =
new StaticPagedList<List<ExpandedUserDTO>>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
See http://www.programering.com/a/MTN2gDNwATM.html
You may need to change List col_UserDTO references to List<ExpandedUserDTO> col_UserDTO
Use this instead
var _UserDTOAsIPagedList =
new StaticPagedList<ExpandedUserDTO>
(
col_UserDTO, intPage, intPageSize, intTotalPageCount
);
I have a patial view with following code(with custom data binding):
Partial View
#{
Html.EnableClientValidation();
Html.EnableUnobtrusiveJavaScript();
var grid = Html.DevExpress().GridView(settings => {
settings.Name = "GridView1";
settings.KeyFieldName = "StudentId";
settings.CallbackRouteValues = new { Controller = "CustomBinding", Action = "MyGridViewPartial" };
settings.CustomActionRouteValues = new { Controller = "Editing", Action = "ChangeEditModePartial" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialAddNew" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialUpdate" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "CustomBinding", Action = "GridView1PartialDelete" };
settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;
settings.SettingsBehavior.ConfirmDelete = true;
settings.SettingsPopup.EditForm.Width = 600;
settings.CommandColumn.Visible = true;
settings.CommandColumn.ShowNewButton = true;
settings.CommandColumn.ShowDeleteButton = true;
settings.CommandColumn.ShowEditButton = true;
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Paging,
new { Controller = "MyController", Action = "MyPagingAction" }
);
settings.CustomBindingRouteValuesCollection.Add(
GridViewOperationType.Sorting,
new { Controller = "MyController", Action = "MySortingAction" }
);
settings.SettingsAdaptivity.AdaptivityMode = GridViewAdaptivityMode.Off;
settings.SettingsAdaptivity.AdaptiveColumnPosition = GridViewAdaptiveColumnPosition.Left;
settings.SettingsAdaptivity.AdaptiveDetailColumnCount = 1;
settings.SettingsAdaptivity.AllowOnlyOneAdaptiveDetailExpanded = false;
settings.SettingsAdaptivity.HideDataCellsAtWindowInnerWidth = 0;
settings.Columns.Add("StudentId");
settings.Columns.Add("StudentName");
settings.Columns.Add("StudentAge");
settings.Columns.Add("StudentGrade");
settings.Columns.Add("StudentAddress");
settings.PreRender = (sender, e) =>
{
((MVCxGridView)sender).StartEdit(0);/**//This is the Exception line**
};
settings.CellEditorInitialize = (s, e) =>
{
ASPxEdit editor = (ASPxEdit)e.Editor;
editor.ValidationSettings.Display = Display.Dynamic;
};
});
if (ViewData["EditError"] != null){
grid.SetEditErrorText((string)ViewData["EditError"]);
}
}
#grid.BindToCustomData(Model).GetHtml()///Custom binding
Please suggest the solutions:
Exception:
A primary key field specified via the KeyFieldName property is not found in the underlying data source. Make sure the field name is spelled correctly. Pay attention to the character case.
Are you sure that the Model contains (StudentId) property and you retrieve it from db successfully and also it is public with getter and setter
I have a 2-steps-form (Fancy Name), but, when I submit this form, the validation return false all time, I debugged it and I receive all the parameters I want, but for some reason the isValid is false and get some error in the RadioButton element, this is the code:
This is the forms/Users.php
public function signup()
{
$contryModel = new Application_Model_Country();
$countries = $contryModel->getCountries();
foreach ($countries as $array)
{
if(isset($array['id_country'])){
$countryArr[$array['id_country']] = $array['country'];
}
}
array_unshift($countryArr, '-- Select Your Country --');
$name = new Zend_Form_Element_Text('Name');
$name->setLabel('Name')
->setRequired(true)
->addValidator('NotEmpty');
$lastname = new Zend_Form_Element_Text('LastName');
$lastname->setLabel('Last Name')
->setRequired(true)
->addValidator('NotEmpty');
$email = new Zend_Form_Element_Text('Email');
$email->setLabel('Email')
->setRequired(true)
->addValidator('NotEmpty');
$website = new Zend_Form_Element_Text('Website');
$website->setLabel('Website')
->setRequired(true)
->addValidator('NotEmpty');
$country = new Zend_Form_Element_Select('Country');
$country->setLabel('Country')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions($countryArr);
$city = new Zend_Form_Element_Select('City');
$city->setLabel('City')
->setRequired(true)
->addValidator('NotEmpty')
->addMultiOptions(array('-- Select Your City --'))
->setRegisterInArrayValidator(false)
->setAttrib('disabled',true);
$password = new Zend_Form_Element_Password('Password');
$password->setLabel('Password')
->setRequired(true)
->addValidator('NotEmpty');
$rpassword = new Zend_Form_Element_Password('RepeatPassword');
$rpassword->setLabel('Repeat Password')
->setRequired(true)
->addValidator('NotEmpty');
$why = new Zend_Form_Element_Textarea('Why');
$why->setRequired(true)
->addValidator('NotEmpty')
->setAttrib('cols', '50')
->setAttrib('rows', '4');
$job = new Zend_Form_Element_Text('Job');
$job->setLabel("Job")
->setRequired(true)
->addValidator('NotEmpty');
$boxes = new Application_Model_Colors();
$res = $boxes->getColors();
foreach($res as $colors){
$colorArr[$colors['id']]['color'] = $colors['color'];
$colorArr[$colors['id']]['overColor'] = $colors['overColor'];
}
$color = new Zend_Form_Element_Radio('color');
$color->setLabel('Color')
->addMultiOptions($colorArr)
->addValidator('NotEmpty');
$save = new Zend_Form_Element_Submit('Submit');
$save->setLabel('Save');
$this->addElements(array($name, $lastname, $email, $website, $password, $rpassword, $job, $country, $city, $color, $why, $save));
}
*This is a part of the view * where I format the Radios
<?php
foreach($this->form->color->options as $key=>$colors){
echo "<label><input type='radio' value='$key' name='color'><div class='registrationBoxes' style='background-color:#".$colors['color']."' data-color='".$colors['color']."' data-overColor='".$colors['overColor']."' value='".$colors['color']."'></div></label>";
}
?>
And here is the Controller
public function indexAction()
{
$form = new Application_Form_Users();
$form->signup();
$this->view->form = $form;
if($this->getRequest()->isPost())
{
$formData = $this->getRequest()->getPost();
if($form->isValid($formData))
{
$formData = $this->getRequest()->getPost();
$name = $formData['Name'];
$lastName = $formData['LastName'];
$email = $formData['Email'];
$website = $formData['Website'];
$password = $formData['Password'];
$rpassword = $formData['RepeatPassword'];
$job = $formData['Job'];
$country = $formData['Country'];
$city = $formData['City'];
$color = $formData['color'];
$why = $formData['Why'];
$date_create = date('Y-m-d H:i:s');
$position = new Application_Model_Country();
$latLong = $position->getLatLong($city);
if($password == $rpassword){
$data = array( 'name'=>$name,
'last_name'=>$lastName,
'email'=>$email,
'website'=>$website,
'password'=>md5($password),
'date_create'=>$date_create,
'job'=>$job,
'country'=>$country,
'city'=>$city,
'color'=>$color,
'why'=>$why,
'latitude'=>$latLong['latitude'],
'longitude'=>$latLong['longitude']
);
$add = new Application_Model_Users();
$res = $add->insertUser($data);
if($res){
$this->view->message = "Registration Successfuly.";
$this->_redirect("/contact");
}else{
$this->view->errorMessage = "We have a problem with your registration, please try again later.";
}
}else{
$this->view->errorMessage = "Password and confirm password don't match.";
$form->populate($formData);
}
} else {
$this->view->errorMessage = "There is an error on your registration, all fields are requried";
$form->populate($formData);
}
}
}
a die(var_dump()) return this:
array(12) {
["Name"]=>
string(9) "Some name"
["LastName"]=>
string(13) "Some lastName"
["Email"]=>
string(21) "Someemail#hotmail.com"
["Password"]=>
string(5) "Some "
["RepeatPassword"]=>
string(5) "Some "
["Website"]=>
string(12) "Some website"
["Job"]=>
string(8) "Some job"
["Country"]=>
string(1) "7"
["City"]=>
string(3) "434"
["color"]=>
string(1) "3"
["Why"]=>
string(10) "Emotional!"
["Submit"]=>
string(4) "Save"
}
As you can see, all the parameters are coming and with value, but for no reason the isValid is returning false, some idea guys?
Thanks.-
EDIT
This is a part of the Zend/form.php code required by Tonunu
public function __construct ($options = null)
{
if (is_array($options)) {
$this->setOptions($options);
} elseif ($options instanceof Zend_Config) {
$this->setConfig($options);
}
// Extensions...
$this->init();
$this->loadDefaultDecorators();
}
public function __clone ()
{
$elements = array();
foreach ($this->getElements() as $name => $element) {
$elements[] = clone $element;
}
$this->setElements($elements);
$subForms = array();
foreach ($this->getSubForms() as $name => $subForm) {
$subForms[$name] = clone $subForm;
}
$this->setSubForms($subForms);
$displayGroups = array();
foreach ($this->_displayGroups as $group) {
$clone = clone $group;
$elements = array();
foreach ($clone->getElements() as $name => $e) {
$elements[] = $this->getElement($name);
}
$clone->setElements($elements);
$displayGroups[] = $clone;
}
$this->setDisplayGroups($displayGroups);
}
public function setOptions (array $options)
{
if (isset($options['prefixPath'])) {
$this->addPrefixPaths($options['prefixPath']);
unset($options['prefixPath']);
}
if (isset($options['elementPrefixPath'])) {
$this->addElementPrefixPaths($options['elementPrefixPath']);
unset($options['elementPrefixPath']);
}
if (isset($options['displayGroupPrefixPath'])) {
$this->addDisplayGroupPrefixPaths(
$options['displayGroupPrefixPath']);
unset($options['displayGroupPrefixPath']);
}
if (isset($options['elementDecorators'])) {
$this->_elementDecorators = $options['elementDecorators'];
unset($options['elementDecorators']);
}
if (isset($options['elements'])) {
$this->setElements($options['elements']);
unset($options['elements']);
}
if (isset($options['defaultDisplayGroupClass'])) {
$this->setDefaultDisplayGroupClass(
$options['defaultDisplayGroupClass']);
unset($options['defaultDisplayGroupClass']);
}
if (isset($options['displayGroupDecorators'])) {
$displayGroupDecorators = $options['displayGroupDecorators'];
unset($options['displayGroupDecorators']);
}
if (isset($options['elementsBelongTo'])) {
$elementsBelongTo = $options['elementsBelongTo'];
unset($options['elementsBelongTo']);
}
if (isset($options['attribs'])) {
$this->addAttribs($options['attribs']);
unset($options['attribs']);
}
$forbidden = array('Options', 'Config', 'PluginLoader', 'SubForms',
'View', 'Translator', 'Attrib', 'Default');
foreach ($options as $key => $value) {
$normalized = ucfirst($key);
if (in_array($normalized, $forbidden)) {
continue;
}
$method = 'set' . $normalized;
if (method_exists($this, $method)) {
$this->$method($value);
} else {
$this->setAttrib($key, $value);
}
}
if (isset($displayGroupDecorators)) {
$this->setDisplayGroupDecorators($displayGroupDecorators);
}
if (isset($elementsBelongTo)) {
$this->setElementsBelongTo($elementsBelongTo);
}
return $this;
}
In order to check if your form is valid, you have to put your data into it, using this method !
$form->setData($formData)
and then you can ask for validation
$form->isValid()
So what you need is :
$formData = $this->getRequest()->getPost();
$form->setData($formData);
if($form->isValid()){
//Blablablabla
}
I am trying to set the width of a DevExpress grid in percentage but the property is not available for me like it is in every example I see. I am using a MasterDetail grid Devexpress version 12.1
settings.Width = Unit.Percentage(100);
How can I set the width property for the whole grid to 100% and then also how would I set the same property for the colums. Here is my grid
#Html.DevExpress().GridView(
settings => {
settings.Name = "masterGrid";
settings.CallbackRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterPartial" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterAddNewPartial" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterUpdatePartial" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "InwardsGoods", Action = "GridViewMasterDeletePartial" };
settings.KeyFieldName = "InwardsGoodsID";
settings.Columns.Add(column =>
{
column.FieldName = "CustomerID";
column.Caption = "Customer";
column.ColumnType = MVCxGridViewColumnType.ComboBox;
var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
comboBoxProperties.DataSource = Model.CustomersList;
comboBoxProperties.TextField = "CustomerName";
comboBoxProperties.ValueField = "CustomerID";
comboBoxProperties.ValueType = typeof(int);
});
settings.Columns.Add(column =>
{
column.FieldName = "CustomerReference";
column.Caption = "Customer Reference";
});
settings.Columns.Add(column =>
{
column.FieldName = "TimberShadeReference";
column.Caption = "TimberShade Reference";
});
settings.Columns.Add(column =>
{
column.FieldName = "DateReceived";
column.Caption = "Date Received";
column.PropertiesEdit.DisplayFormatString = "d";
});
settings.Columns.Add(column =>
{
column.FieldName = "Comment";
column.Caption = "Comment";
});
settings.SettingsDetail.AllowOnlyOneMasterRowExpanded = true;
settings.SettingsDetail.ShowDetailRow = true;
settings.CommandColumn.Visible = true;
settings.CommandColumn.NewButton.Visible = true;
settings.CommandColumn.DeleteButton.Visible = true;
settings.CommandColumn.EditButton.Visible = true;
settings.SetDetailRowTemplateContent(c =>
{
Html.RenderAction("GridViewDetailPartial", new { inwardsgoodsID = DataBinder.Eval(c.DataItem, "InwardsGoodsID") });
});
//TO OPEN THE FIRST EDITABLE ROW
//settings.PreRender = (sender, e) =>
//{
// ((MVCxGridView)sender).DetailRows.ExpandRow(0);
//};
}).Bind(Model.InwardsGoods).GetHtml()
Ok so I found the answer. What I did to solve this was at the top of the cshtml page I added this using statement.
#using System.Web.UI.WebControls;