How to insert multiple RadioButtonFor value into database - asp.net

I want to insert 3 value of radio button into Database using MVC.
User need to select one material for each categories(Walls,Roof,Floor)
Currently the user can only select one value (may need to do grouping).But when I do grouping only the structInfo value is inserted into database. I need all the 3 value inserted into database.
This is how the database design look like
the struct inf(walls,roof,floor) the materialinfo is (bricks.concrete,woods, etc)
So can I make all the 3 value choosed by user save into database?
This is my view
#foreach (var structIN in Model.structInfo)
{
if (structIN.structId.Equals(1))
{
#Html.Label(structIN.structNm) #:
foreach (var material in Model.materialInfo)
{
if (material.materialId.Equals(1) || material.materialId.Equals(2) || material.materialId.Equals(3))
{
#Html.RadioButtonFor(model => model.buildInfo.materialId, material.materialId)#Html.Label(material.materialNm)
#Html.HiddenFor(model => model.buildInfo.structId, new { Value = structIN.structId })
}
}
}
else if(structIN.structId.Equals(2))
{
<br />
#Html.Label(structIN.structNm) #:
foreach (var material2 in Model.materialInfo)
{
if (material2.materialId.Equals(2) || material2.materialId.Equals(4) || material2.materialId.Equals(5))
{
#Html.RadioButtonFor(model2 => model2.buildInfo.materialId, material2.materialId)#Html.Label(material2.materialNm)
#Html.HiddenFor(model2 => model2.buildInfo.structId, new { Value = structIN.structId })
}
}
}
else if (structIN.structId.Equals(3))
{
<br />
#Html.Label(structIN.structNm) #:
foreach (var material3 in Model.materialInfo)
{
if (material3.materialId.Equals(6) || material3.materialId.Equals(3))
{
#Html.RadioButtonFor(model3 => model3.buildInfo.materialId, material3.materialId) #Html.Label(material3.materialNm)
#Html.HiddenFor(model3 => model3.buildInfo.structId, new { Value = structIN.structId })
}
}
}
}

my GET method
[HttpGet]
public ActionResult RegisterForm()
{
PopulateStructMaterialData();
using (var dataBase = new TMXEntities())
{
var model = new RegisterInfoPA()
{
//OTHER CODES
};
return View(model);
}
}
Populating Data
private void PopulateStructMaterialData()
{
var list = new List<strucMaterial>
{
new strucMaterial{ifOthers = "", materialId = 1, materialNm = "Bricks", structId = 1, structNm = "Walls", insuranceReqId = 0, isSelected = false},
new strucMaterial{ifOthers = "", materialId = 2, materialNm = "Concrete", structId = 1, structNm = "Walls", insuranceReqId = 0, isSelected = false},
new strucMaterial{ifOthers = "", materialId = 3, materialNm = "Woods", structId = 1, structNm = "Walls", insuranceReqId = 0, isSelected = false},
new strucMaterial{ifOthers = "", materialId = 2, materialNm = "Concrete", structId = 2, structNm = "Roof", insuranceReqId = 0, isSelected = false},
new strucMaterial{ifOthers = "", materialId = 4, materialNm = "Tiles", structId = 2, structNm = "Roof", insuranceReqId = 0, isSelected = false},
new strucMaterial{ifOthers = "", materialId = 5, materialNm = "Zinc", structId = 2, structNm = "Roof", insuranceReqId = 0, isSelected = false},
new strucMaterial{ifOthers = "", materialId = 3, materialNm = "Woods", structId = 3, structNm = "Floor", insuranceReqId = 0, isSelected = false},
new strucMaterial{ifOthers = "", materialId = 6, materialNm = "Reinforced Concrete", structId = 3, structNm = "Floor", insuranceReqId = 0, isSelected = false},
};
ViewBag.populatebuilding = list;
}
In View
List<Insurance.ViewModels.strucMaterial> viewModelSM = ViewBag.populatebuilding;
for(int i=0; i<viewModelSM.Count; i++)
{
#Html.DisplayFor(m => viewModelSM[i].structNm)
#Html.HiddenFor(m => viewModelSM[i].structId)
#Html.CheckBoxFor(m => viewModelSM[i].isSelected)
#Html.HiddenFor(m => viewModelSM[i].materialId)
#Html.Label(viewModelSM[i].materialNm)
}
My POST method
[HttpPost]
public ActionResult RegisterForm(RegisterInfoPA viewmodel, List<strucMaterial> list)
{
using (var dataBase = new TMXEntities())
{
var model = new RegisterInfoPA()
{
//OTHER CODES
};
if (ModelState.IsValid)
{
//OTHER CODES
var register = viewmodel.reg;
var personalinfo = viewmodel.pinfo;
//Save Register
db.registers.Add(register);
db.SaveChanges();
//Retriving required Id's
var getid = register.registrationId;
var getRegTypeID = register.regisTypeId;
//SAVE PERSONAL INFO
personalinfo.registrationId = getid;
db.personalInfoes.Add(personalinfo);
db.SaveChanges();
//---HOW SHOULD I SAVE THE CHECKBOX HERE?-----------
**> tHIS IS MY CODE, BUT IT IS NOT WORKING**
foreach(var item in list) (<< error starts here)
{
buildingInfo.materialId = item.materialId;
buildingInfo.structId = item.structId;
buildingInfo.insuranceReqId = item.insuranceReqId;
db.buildingInfoes.Add(buildingInfo);
}
db.SaveChanges();
}
}
}
I am always getting this error
System.NullReferenceException: Object reference not set to an instance of an object.
How the proper code should look like? Thank you.

Related

Mocking of Where method in Data Repository is returning null at its actual implementation in repository

I have written a test for edit model of a class in EF core.
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList();
if(expense != null)
{
expense.ForEach(x =>
{
x.Name = model.Name;
x.AddedOn = model.AddedOn;
x.Amount = model.Amount;
x.Type = model.Type;
x.SplitOption = model.SplitOption;
x.Notes = model.Notes;
x.IsGroupExpense = model.IsGroupExpense;
});
return expense.FirstOrDefault();
}
else
{
return null;
}
}
I want to test this method using xUnit and Moq and I have also written a method for it as below.
[Fact]
public async void UnitTest_IsExpenseEdited_ReturnsTrue()
{
var expenseCurrent = new Expense()
{
Id = 5,
Name = "Test Expense",
Amount = 1500,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "",
IsDeleted = false,
IsGroupExpense = false,
SplitOption = 1,
Type = 0
};
var expenseList = (new List<Expense>{ expenseCurrent });
var expenseAfterEdit = new Expense()
{
Id = 5,
Name = "Test Expense Edited",
Amount = 2000,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "Edited !!!",
IsDeleted = false,
IsGroupExpense = true,
SplitOption = 2,
Type = 0
};
_dataRepositoryMock.Setup(x => x.Where<Expense>(a => a.Id == expenseCurrent.Id)).Returns(expenseList as IQueryable<Expense>);
var expenseEdited = await _exepenseRepository.EditExpense(expenseAfterEdit);
Assert.Equal(expenseEdited, expenseAfterEdit);
}
But here, the Where method is returning null
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList(); in repository
}
I am getting var expense null in above code.
Please suggest what should I include in the code to get the value in above var expense?
To test this method, I want to create a fake data which is going to be updated. Please suggest how this thing needs to be written properly?

ASP.NET gridview to JSON

So I am looking at converting a GridView (with data from an Oracle database) to JSON file, which is then used in Highcharts chart.
So far, I have Newtonsoft.JSON and have seen multiple tutorials with converting datatables to JSON, but am unable to get gridview to JSON (see How to convert gridview data to Json? for reference to code I have).
<script src="~/Scripts/jquery.base64.js"></script>
<script src="~/Scripts/tableExport.js"></script>
<script src="~/Scripts/jspdf/libs/base64.js"></script>
<script src="~/Scripts/jspdf/jspdf.js"></script>
<script src="~/Scripts/jspdf/FileSaver.js"></script>
<script src="~/Scripts/jspdf/jspdf.plugin.cell.js"></script>
function ExportTpGridtoPDF(divid) {
var table1 =
tableToJson($('#' + divid + ' .grid-table').get(0)),
cellWidth = 35,
rowCount = 0,
cellContents,
leftMargin = 10,
topMargin = 15,
topMarginTable = 5,
headerRowHeight = 13,
rowHeight = 13,
l = {
orientation: 'l',
unit: 'mm',
format: 'a3',
compress: true,
fontSize: 8,
lineHeight: 1,
autoSize: false,
printHeaders: true
};
var doc = new jsPDF(l, '', '', '');
doc.setProperties({
title: 'Test PDF Document',
subject: 'This is the subject',
author: 'author',
keywords: 'generated, javascript, web 2.0, ajax',
creator: 'author'
});
doc.cellInitialize();
$.each(table1, function (i, row) {
rowCount++;
$.each(row, function (j, cellContent) {
if (rowCount == 1) {
doc.margins = 1;
doc.setFontSize(12);
doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
}
else if (rowCount == 2) {
doc.margins = 1;
doc.setFontSize(12);
doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
}
else {
doc.margins = 1;
doc.setFontSize(12);
doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
}
})
})
doc.save('sample Report.pdf');
}
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
if (table.rows[0].cells[i].innerHTML != "") {
headers[i] = table.rows[0].cells[i].innerText.toLowerCase().replace(/ /gi, '');
}
}
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 1; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerText;
}
data.push(rowData);
}
return data;
}

How to add Category names in search in Nopcommerce 3.8

Hi there i would like to let customers type a category name and get some search results. Currently when you type a category name it says no results.
public ActionResult AdvanceSearch(SearchModel model, CatalogPagingFilteringModel command)
{
//'Continue shopping' URL
_genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
SystemCustomerAttributeNames.LastContinueShoppingPage,
_webHelper.GetThisPageUrl(false),
_storeContext.CurrentStore.Id);
if (model == null)
model = new SearchModel();
var searchTerms = model.q;
if (searchTerms == null)
searchTerms = "";
searchTerms = searchTerms.Trim();
//sorting
PrepareSortingOptions(model.PagingFilteringContext, command);
//view mode
PrepareViewModes(model.PagingFilteringContext, command);
//page size
PreparePageSizeOptions(model.PagingFilteringContext, command,
_catalogSettings.SearchPageAllowCustomersToSelectPageSize,
_catalogSettings.SearchPagePageSizeOptions,
_catalogSettings.SearchPageProductsPerPage);
string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY,
_workContext.WorkingLanguage.Id,
string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var categories = _cacheManager.Get(cacheKey, () =>
{
var categoriesModel = new List<SearchModel.CategoryModel>();
//all categories
var allCategories = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id);
foreach (var c in allCategories)
{
//generate full category name (breadcrumb)
string categoryBreadcrumb = "";
var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService);
for (int i = 0; i <= breadcrumb.Count - 1; i++)
{
categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
if (i != breadcrumb.Count - 1)
categoryBreadcrumb += " >> ";
}
categoriesModel.Add(new SearchModel.CategoryModel
{
Id = c.Id,
Breadcrumb = categoryBreadcrumb
});
}
return categoriesModel;
});
if (categories.Any())
{
//first empty entry
model.AvailableCategories.Add(new SelectListItem
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
//all other categories
foreach (var c in categories)
{
model.AvailableCategories.Add(new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Breadcrumb,
Selected = model.cid == c.Id
});
}
}
IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
// only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
if (Request.Params["q"] != null)
{
if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength)
{
model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
}
else
{
var categoryIds = new List<int>();
int manufacturerId = 0;
decimal? minPriceConverted = null;
decimal? maxPriceConverted = null;
bool searchInDescriptions = false;
int vendorId = 0;
if (model.adv)
{
//advanced search
var categoryId = model.cid;
if (categoryId > 0)
{
categoryIds.Add(categoryId);
if (model.isc)
{
//include subcategories
categoryIds.AddRange(GetChildCategoryIds(categoryId));
}
}
manufacturerId = model.mid;
//min price
if (!string.IsNullOrEmpty(model.pf))
{
decimal minPrice;
if (decimal.TryParse(model.pf, out minPrice))
minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
}
//max price
if (!string.IsNullOrEmpty(model.pt))
{
decimal maxPrice;
if (decimal.TryParse(model.pt, out maxPrice))
maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
}
if (model.asv)
vendorId = model.vid;
searchInDescriptions = model.sid;
}
//var searchInProductTags = false;
var searchInProductTags = searchInDescriptions;
//products
products = _productService.SearchProducts(
categoryIds: categoryIds,
manufacturerId: manufacturerId,
storeId: _storeContext.CurrentStore.Id,
visibleIndividuallyOnly: true,
priceMin: minPriceConverted,
priceMax: maxPriceConverted,
keywords: searchTerms,
//searchDescriptions: searchInDescriptions,
searchProductTags: searchInProductTags,
searchSku: true,
languageId: _workContext.WorkingLanguage.Id,
orderBy: (ProductSortingEnum)command.OrderBy,
pageIndex: command.PageNumber - 1,
pageSize: command.PageSize,
vendorId: vendorId);
model.Products = PrepareProductOverviewModels(products).ToList();
model.NoResults = !model.Products.Any();
//search term statistics
if (!String.IsNullOrEmpty(searchTerms))
{
var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id);
if (searchTerm != null)
{
searchTerm.Count++;
_searchTermService.UpdateSearchTerm(searchTerm);
}
else
{
searchTerm = new SearchTerm
{
Keyword = searchTerms,
StoreId = _storeContext.CurrentStore.Id,
Count = 1
};
_searchTermService.InsertSearchTerm(searchTerm);
}
}
//event
_eventPublisher.Publish(new ProductSearchEvent
{
SearchTerm = searchTerms,
SearchInDescriptions = searchInDescriptions,
CategoryIds = categoryIds,
ManufacturerId = manufacturerId,
WorkingLanguageId = _workContext.WorkingLanguage.Id,
VendorId = vendorId
});
}
}
model.PagingFilteringContext.LoadPagedList(products);
return View(model);
}
A public action method 'AdvanceSearch' was not found on controller 'Nop.Web.Controllers.CatalogController'.

Multiple setups for a mockset ASP.net only carries out 1 mock

So my problem is that I've got to mock two things. One is a method that finds a person and the other is a list of those people over which it iterates. However it doesn't get both setups but only 1. I've tried putting them in different orders and each time only the top 1 works.
here's my code:
Person test = new Person()
{
City = "Eindhoven Area, Netherlands.",
userid = 1,
ID = 1,
Email = "fraylight#gmail.com",
ExtraInfo = "blabla",
HobbyProjectICTRelated = "a",
Hobbys = "",
LearntSkillsAndLevelOfSkills = "Java:7, C#:4, Software Documentation:4, Software Development:4, HTML:2, CSS:2, jQuery:1",
Name = "Marijn van Donkelaar",
PhoneNr = "0612345678",
ProfileImage = "/Images/hollemar.jpg",
SkillsToLearn = "ASP.net:2, JAVA:3",
Stand = "",
Summary = "",
YearsOfWorkExperience = 6,
PeopleManagerApproved = true,
PeopleManager = "Richard"
};
Person test1 = new Person()
{
City = "Eindhoven Area, Netherlands.",
userid = 2,
ID = 2,
Email = "fraylight#gmail.com",
ExtraInfo = "",
HobbyProjectICTRelated = "a",
Hobbys = "zwemmen",
LearntSkillsAndLevelOfSkills = "Java:8, C#:4, Software Documentation:4, Software Development:4, HTML:2, CSS:2, jQuery:1",
Name = "Richard Holleman",
PhoneNr = "",
ProfileImage = "/Images/hollemar.jpg",
SkillsToLearn = "ASP.net:2, JAVA:2",
Stand = "",
Summary = "",
YearsOfWorkExperience = 16,
PeopleManagerApproved = true,
PeopleManager = "Richard"
};
Person test2 = new Person()
{
City = "Eindhoven Area, Netherlands.",
userid = 3,
ID = 3,
Email = "fraylight#gmail.com",
ExtraInfo = "",
HobbyProjectICTRelated = "",
Hobbys = "zwemmen",
LearntSkillsAndLevelOfSkills = "C#:4, SQL:4, PLSQL:4, HTML:2, CSS:2, jQuery:1",
Name = "Jasmine Test",
PhoneNr = "0612345678",
ProfileImage = "/Images/hollemar.jpg",
SkillsToLearn = "ASP.net:2, JAVA:1",
Stand = "",
Summary = "",
YearsOfWorkExperience = 11,
PeopleManagerApproved = true,
PeopleManager = "Richard"
};
var data = new List<Person> { test, test1, test2 }.AsQueryable();
var dbSetMock = new Mock<IDbSet<Person>>();
dbSetMock.Setup(m => m.Provider).Returns(data.Provider);
dbSetMock.Setup(m => m.Expression).Returns(data.Expression);
dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType);
dbSetMock.Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator());
var mockContext = new Mock<PersonDBContext>();
mockContext.Setup(x => x.Persons).Returns(dbSetMock.Object);
mockContext.Setup(x => x.Persons.Find(1)).Returns(test);
var service = new PersonController(mockContext.Object);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext.Session["loggedinuser"]).Returns(10);
service.ControllerContext = controllerContext.Object;
ViewResult detailspageresultcorrect = (ViewResult) service.Details(10);
Person resultpersoncorrect = (Person) detailspageresultcorrect.Model;
Assert.IsTrue(resultpersoncorrect.Name.Equals(test.Name));
The part where it goes wrong is on the line of: var mockContext = new Mock();
You should be able to mock the Find method directed on the IDbSet instead of going via the Persons property.
So your setups would look like the following:
var dbSetMock = new Mock<IDbSet<Person>>();
dbSetMock.Setup(m => m.Provider).Returns(data.Provider);
dbSetMock.Setup(m => m.Expression).Returns(data.Expression);
dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType);
dbSetMock.Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator());
dbSetMock.Setup(m => m.Find(1)).Returns(test);
var mockContext = new Mock<PersonDBContext>();
mockContext.Setup(x => x.Persons).Returns(dbSetMock.Object);

MvcxGridview with datatype System.Byte[]

I'm using MvcxGridView to bind a DataTable model and I have a problem with a DataColumn with datatype System.Byte[].
When I view data, gridview does not show a value and only displays System.Byte[]. I want the GridView to display a picture in that column.
When I save data, I get this message:
Invalid cast from 'System.String' to 'System.Byte[]'
How can I solve these problems?
Here is my code in view:
#using System.Data;
#model TestPA6MVC.Models.EntityModelForViewDataSettingGrid
#functions{
MVCxGridViewCommandColumn CreateCommandColumn(string AllowEdit,string AllowAdd)
{
MVCxGridViewCommandColumn column = new MVCxGridViewCommandColumn();
column.Visible = true;
column.NewButton.Visible = (AllowAdd.ToLower()=="true")?true:false;
column.DeleteButton.Visible = (AllowEdit.ToLower() == "true") ? true : false; ;
//column.EditButton.Visible = true;
return column;
}
}
#{
var grid = Html.DevExpress().GridView(
settings => {
settings.Name = "gvEditing";
settings.CallbackRouteValues = new {
Controller = "Home", Action = "GridViewPartial",
ViewName = Model.ViewName,
PrimaryKeyCollection = Model.PrimaryKeyCollection,
TableEditorList = Model.TableEditorList,
ColumnComboBoxCollection = Model.ColumnComboBoxCollection,
ColumnReadOnlyCollection = Model.ColumnReadOnlyCollection,
ColumnHideCollection = Model.ColumnHideCollection,
ParamNameCollection = Model.ParamNameCollection,
DataForParamCollection = Model.DataForParamCollection,
ParamTypeCollection = Model.ParamTypeCollection,
AllowAdd = Model.AllowAdd,
AllowEdit = Model.AllowEdit
};
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "GridViewPartialAddNew", ViewName = Model.ViewName };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "GridViewPartialUpdate", ViewName = Model.ViewName };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "GridViewPartialDelete", ViewName = Model.ViewName };
settings.SettingsEditing.BatchUpdateRouteValues = new {
Controller = "Home", Action = "BatchEditingUpdateModel",
ViewName = Model.ViewName,
PrimaryKeyCollection = Model.PrimaryKeyCollection,
TableEditorList = Model.TableEditorList,
ColumnComboBoxCollection = Model.ColumnComboBoxCollection,
ColumnReadOnlyCollection = Model.ColumnReadOnlyCollection,
ColumnHideCollection = Model.ColumnHideCollection,
ParamNameCollection = Model.ParamNameCollection,
DataForParamCollection = Model.DataForParamCollection,
ParamTypeCollection = Model.ParamTypeCollection,
AllowAdd = Model.AllowAdd,
AllowEdit = Model.AllowEdit
};
if (Model.AllowEdit.ToLower() == "true")
{
settings.SettingsEditing.Mode = GridViewEditingMode.Batch;//Kieu view chinh sua
}
else { settings.SettingsEditing.Mode = GridViewEditingMode.PopupEditForm; }
settings.SettingsBehavior.ConfirmDelete = true;//Cho phep hien thi thong bao xac nhan
settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;//Cho phep chinh sua do rong cot
settings.Width = 800;//Chieu rong cua gridview
settings.Settings.HorizontalScrollBarMode = ScrollBarMode.Auto;
settings.SettingsPager.Mode = GridViewPagerMode.ShowPager;
settings.SettingsPager.PageSize = 50;
settings.Settings.VerticalScrollableHeight = 300;
settings.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.Settings.ShowHeaderFilterButton = true;//Hien thi bo loc cho column
//Tao cot gia de tranh tinh trang hien thi lai cac Column an khi Callback
MVCxGridViewColumn fakeco = new MVCxGridViewColumn();
fakeco.Visible = false;
fakeco.Width = 0;
fakeco.EditFormSettings.Visible = DefaultBoolean.False;
settings.Columns.Add(fakeco);
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.DataBound = (sender, e) =>
{
//Build Column Tool Automatic
((MVCxGridView)sender).Columns.Insert(0, CreateCommandColumn(Model.AllowEdit,Model.AllowAdd));
//Add custom Column
foreach (var child in Model.ModelForDisplayColumnList)
{
MVCxGridViewColumn dc = new MVCxGridViewColumn();
dc.Caption = child.Caption;
dc.FieldName = child.ColumnName;
if(child.IsHidden)//Neu de an hoan toan se khong lay duoc du lieu da chinh sua
{ dc.Width = 0; }
//dc.Visible = !child.IsHidden;
dc.ReadOnly = child.IsReadOnly;
switch (child.DataType)
{
case "datetime":
dc.ColumnType = MVCxGridViewColumnType.DateEdit;
var DateEditProperties = dc.PropertiesEdit as DateEditProperties;
DateEditProperties.DisplayFormatString = "dd/MM/yyyy hh:mm tt";
//Cho phep chinh ngay, gio
DateEditProperties.UseMaskBehavior = true;
//Dinh dang hien thi khi chinh sua
DateEditProperties.EditFormat = EditFormat.Custom;
DateEditProperties.EditFormatString = "dd/MM/yyyy hh:mm tt";
DateEditProperties.TimeSectionProperties.Visible = true;//Hien khung chinh gio
break;
case "combobox":
dc.ColumnType = MVCxGridViewColumnType.ComboBox;
var DropDownEditProperties = dc.PropertiesEdit as ComboBoxProperties;
DropDownEditProperties.DataSource = child.DataSourceForComboBoxColumn;
DropDownEditProperties.ValueField = child.DataSourceForComboBoxColumn.Columns[0].ColumnName;
DropDownEditProperties.TextFormatString = "{0}";
foreach (DataColumn childcolumn in child.DataSourceForComboBoxColumn.Columns)
{
DropDownEditProperties.Columns.Add(childcolumn.ColumnName, childcolumn.ColumnName);
}
break;
case "boolean":
case "bit":
dc.ColumnType = MVCxGridViewColumnType.CheckBox;
break;
case "byte[]":
dc.ColumnType = MVCxGridViewColumnType.BinaryImage;
//var ImageEditProperties = dc.PropertiesEdit as BinaryImageEditProperties;
//ImageEditProperties.ImageWidth = 50;
//ImageEditProperties.ImageHeight = 50;
break;
//case "string":
// dc.ColumnType = MVCxGridViewColumnType.ComboBox;
// var ComboBoxEditProperties = dc.PropertiesEdit as ComboBoxProperties;
// ComboBoxEditProperties.DataSource = ModelForDisplayColumnList;
// ComboBoxEditProperties.TextField = "DataType";
// ComboBoxEditProperties.ValueField = "Caption";
// break;
}
((MVCxGridView)sender).Columns.Add(dc);
}
};
settings.KeyFieldName = Model.PrimaryKeyCollection;
});
if (ViewData["EditError"] != null){
grid.SetEditErrorText((string)ViewData["EditError"]);
}
}
#grid.Bind(Model.DataSourceForGrid).GetHtml()

Resources