i have some task: I have a List that I pass in View from Controller, But this model in itself is a collection. How should I bind a column in the method of constructing?
c#:
public static void GridColumns(List<ParameterCollection> model, MVCxGridViewColumnCollection columns)
{
columns.Add(??????????);
}
View:
#model List<TFlex.DOCs.Model.Parameters.ParameterCollection>
#using TFlexDOCsWeb;
#Html.DevExpress().GridView(settings =>
{
settings.Name = "GridView";
//settings.ClientSideEvents.Init = "OnInit";
settings.KeyFieldName = "SystemFields.Id";
settings.SettingsBehavior.ConfirmDelete = true;
settings.CallbackRouteValues = new { Controller = "Catalogues", Action = "_GridViewPartial" };
settings.CommandColumn.Visible = true;
settings.CommandColumn.Caption = "*";
settings.CommandColumn.Width = System.Web.UI.WebControls.Unit.Percentage(5);
settings.SettingsPager.Visible = true;
settings.SettingsBehavior.AllowSelectByRowClick = false;
TFlexDOCsWeb.DevEx.GridViewBuilding.<bold>GridColumns</bold>(Model, settings.Columns);
var headerFilterMode = true ? HeaderFilterMode.CheckedList : HeaderFilterMode.List;
foreach (GridViewDataColumn column in settings.Columns)
column.Settings.HeaderFilterMode = headerFilterMode;
settings.Settings.ShowFilterRow = true;
settings.Settings.ShowFilterRowMenu = true;
}).Bind(Model).GetHtml()<bold>
</bold>
model ParameterCollection consist from , where parameter.Value = is value, and parameter.ParameterInfo = Caption of this parameter(name of field). I Dont know how to bind column names for each ParameterCollection Parameter.parameterInfo.name
You just bind it to the name of the property on the object(s) that your list holds in the column settings where you make your gridviewsettings.
See below simplified example.
MODEL
namespace Some.Name.Space
{
public class RecipientListViewModel : List<RecipientViewModel> // HOwever you define your list
{
}
public class RecipientViewModel
{
public string Id {get; set;}
public string FullName { get; set; }
}
}
VIEW
#Html.DevExpress().GridView(settings =>
{
//General settings
settings.Name = "GridViewName";
settings.KeyFieldName = "Id"; // actual parameter name of keyfield on your object that is in your list
//other settings etc
settings.Columns.Add(column =>
{
column.Name = "FullName"; // actual parameter name on your object that is in your list that you want on the column
column.FieldName = "FullName"; // actual parameter name on your object that is in your list that you want on the column
column.Caption = LanguageHelper.GetText("UserConfig_Recipients_RecipientNameHeader");
//column.Width = System.Web.UI.WebControls.Unit.Pixel(200);
});
//other columns etc
}).Bind(YourModel).GetHtml()
CONTROLLER
public ActionResult Overview()
{
RecipientListViewModel model = PopulateInformationView(); // Populates the list with data
return View("YOURVIEWNAME", model);
}
Related
i'm trying to create an application where data in a list must be inserted into a database table at once. I made some research and found out that this is possible using user-defined table types where in c# a datatable is used and passed to a stored procedure that is executed. now my problem is that there are no data tables in Xamarin.Android. so I thought to use a list instead. my idea was to create a list in the application and pass it to the webservice method, and in my webservice method I receive the list and convert it to a datatable then pass it as a parameter to the stored procedure. I wrote the following codes:
in my webservice:
[WebMethod]
public bool insrt_dt(List<Class1> lst)
{
SqlParameter param;
SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);
DataTable dt = list_to_dt(lst);
SqlCommand cmd = new SqlCommand("Insert_Customers", conn);
cmd.CommandType = CommandType.StoredProcedure;
if (conn.State == System.Data.ConnectionState.Closed)
{
conn.Open();
}
param = new SqlParameter("#tblcustomers", dt);
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
cmd.Parameters.Add(param);
cmd.CommandTimeout = 300;
int a=cmd.ExecuteNonQuery();
if (a > 0)
{
return true;
}
else return false;
}
}
Class1:
public class Class1
{
public int id { get; set; }
public string name { get; set; }
public string country { get; set; }
}
in my Xamarin.Android app
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button btn = FindViewById<Button>(Resource.Id.button1);
btn.Click += delegate
{
wr.WebService1 ws = new wr.WebService1();
wr.Class1 class1 = new wr.Class1();
List<wr.Class1> lst = new List<wr.Class1>(){
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
ws.insrt_dt(lst);
ws.insrt_dtCompleted += Ws_insrt_dtCompleted;
};
}
private void Ws_insrt_dtCompleted(object sender, wr.insrt_dtCompletedEventArgs e)
{
bool l = e.Result;
if (l == true)
Toast.MakeText(this, "khh", ToastLength.Long).Show();
else
Toast.MakeText(this, "ijo'pioo", ToastLength.Long).Show();
}
}
but I keep getting this error:
Argument 1: cannot convert from 'System.Collections.Generic.List<app_dt.wr.Class1>' to 'app_dt.wr.Class1[]
so I used these lines instead
new wr.Class1() { id = 1, name = "hgf", country = "khg" },
new wr.Class1() { id = 2, name = "hgf", country = "khg"} };
wr.Class1[] class1s = lst.ToArray();
ws.insrt_dt(class1s);
now I don't get an error, but it doesn't work, I mean why does it say that the webservice method input must be an array and I've created it as a list. any suggestions for this?
As i know, Xamarin do not support System.Data.SqlClient. If you want to use the database for the Xamarin android project, you could use the SQLite.NET.
Install the package from the NuGet.
NuGet: sqlite-net-pcl https://www.nuget.org/packages/sqlite-net-pcl/
For the code sample about how to use the database in Xamarin, you could check the link below. https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows
For Xamarin.Android, you could check the sample code in the link below. https://learn.microsoft.com/en-us/xamarin/android/data-cloud/data-access/using-sqlite-orm
I have a custom TagHelper which extends the OOTB InputTagHelper. I am conditionally adding attributes to it based on the presence of a custom ValidationAttribute on the model property associated with it. The code for this in the TagHelper .Process method works fine:
if (this.For.Metadata.ValidatorMetadata.OfType<NumericValidationAttribute>().Any())
{
output?.Attributes.SetAttribute(new TagHelperAttribute("inputmode", "numeric"));
output?.Attributes.SetAttribute(new TagHelperAttribute("pattern", "[0-9]*"));
}
My issue is in Unit Testing this. I have other Unit Tests written using the code available in the Net Core MVC Test repo: https://github.com/aspnet/Mvc/blob/master/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/
... but there's no real steer on how to create the For i.e ModelExpression for the property I want to test which has this Validation attribute associated with it: e.g.
public class TestModel
{
[NumericValidation(ErrorMessage = "Error message")]
public string Field1 { get; set; }
}
I want to be able to populate the For.Metadata.ValidatorMetadata list for this ModelExpression and I don't know how.
The full Unit Test which doesnt work is:
[Fact]
public void CustomInputTagHelperProcess_NumericValidationAttributeOnModelProperty_GeneratesCorrectHtml()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var model = new TestModel
{
Field1 = "cc",
};
var modelExplorer = metadataProvider.GetModelExplorerForType(typeof(TestModel), model);
var modelExpression = new ModelExpression(name: "Field1", modelExplorer: modelExplorer);
var viewContext = TestableHtmlGenerator.GetViewContext(model, metadataProvider);
var attributes = new TagHelperAttributeList
{
{ "name", PropertyName },
{ "type", InputTypeName },
};
var tagHelperContext = new TagHelperContext(attributes, new Dictionary<object, object>(), nameof(CustomInputTagHelperTest));
var output = new TagHelperOutput(
Input,
new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(result: null))
{
TagMode = TagMode.SelfClosing,
};
var customInputTagHelper = new CustomInputTagHelper(this.htmlGenerator)
{
For = this.modelExpression,
InputTypeName = InputTypeName,
Name = PropertyName,
ViewContext = this.viewContext,
};
// Act
customInputTagHelper.Process(this.tagHelperContext, output);
// Assert - ensure we have an inputmode attribute on the input.
Assert.Contains(output.Attributes, x => x.Name == "inputmode" && x.Value.ToString() == "numeric");
}
Any thoughts?
There is a custom field, that I declared for the Customer DAC:
public class CustomerExt : PXCacheExtension<Customer>
{
#region UsrDemoField
[PXDBString(255)]
[PXUIField(DisplayName = "Demo Field")]
public virtual string UsrDemoField { get; set; }
public abstract class usrDemoField : IBqlField { }
#endregion
}
Attempts to modify the ARInvoice Customer selector with the Customize Selector Columns popup didn't seem to work. How can I add my custom field into the ARInvoice customer selector?
Be aware, since Acumatica ERP build #17.201.0043, it's possible to customize the list of columns defined for AR Invoices' Customer lookup via the Customize Selector Columns dialog (available in the Data Class section of the Customization Manager). For step-by-step instructions please check the screenshot below:
To modify AR Invoices' Customer lookup on Acumatica ERP ver. 6.1 and earlier, please follow the steps below:
The definition of PXCustomizeSelectorColumns generated by the Customize Selector Columns popup brilliantly works with the majority of selectors inside Acumatica ERP. Basically, PXCustomizeSelectorColumns simply replaces originally defined columns for a selector with the custom set of columns during an initialization of PXCache:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false)]
public class PXCustomizeSelectorColumns: PXEventSubscriberAttribute
{
private readonly Type[] _columns;
public PXCustomizeSelectorColumns(params Type[] columns)
{
_columns = columns;
}
public override void CacheAttached(PXCache cache)
{
cache.SetAltered(this.FieldName, true);
foreach (PXEventSubscriberAttribute attr in cache.GetAttributes(null, this.FieldName))
{
PXSelectorAttribute sel = attr as PXSelectorAttribute;
if (sel == null)
continue;
sel.SetFieldList(_columns);
sel.Headers = null;
}
}
}
So what can cause the PXCustomizeSelectorColumns attribute to fail and not replace selector's originally defined columns? Any time the SetColumns method is executed on an instance of PXDimensionSelectorAttribute or PXSelectorAttribute after PXCache was initialized, there is no chance for PXCustomizeSelectorColumns to do its job.
[PXDBInt()]
[PXUIField(DisplayName = "Customer", Visibility = PXUIVisibility.Visible)]
[Serializable]
public class CustomerAttribute : AcctSubAttribute
{
...
public virtual void FieldSelecting(PXCache sender, PXFieldSelectingEventArgs e)
{
if (this.AttributeLevel == PXAttributeLevel.Item || e.IsAltered)
{
PopulateFields(sender);
}
PXFieldSelecting handler = GetAttribute<PXDimensionSelectorAttribute>().FieldSelecting;
handler(sender, e);
}
protected virtual void PopulateFields(PXCache sender)
{
if (_FieldList == null)
{
_FieldList = new string[this._fields.Length];
_HeaderList = new string[this._fields.Length];
for (int i = 0; i < this._fields.Length; i++)
{
Type cacheType = BqlCommand.GetItemType(_fields[i]);
PXCache cache = sender.Graph.Caches[cacheType];
if (cacheType.IsAssignableFrom(typeof(BAccountR)) ||
_fields[i].Name == typeof(BAccountR.acctCD).Name ||
_fields[i].Name == typeof(BAccountR.acctName).Name)
{
_FieldList[i] = _fields[i].Name;
}
else
{
_FieldList[i] = cacheType.Name + "__" + _fields[i].Name;
}
_HeaderList[i] = PXUIFieldAttribute.GetDisplayName(cache, _fields[i].Name);
}
}
var attr = GetAttribute<PXDimensionSelectorAttribute>().GetAttribute<PXSelectorAttribute>();
attr.SetColumns(_FieldList, _HeaderList);
}
...
}
With that said, to add a custom field into the ARInvoice Customer selector, one should replace all attributes declared for the ARInvoice.CustomerID field and redefine columns for the Customer selector within the CustomerActive attribute:
[PXDefault()]
[CustomerActive(typeof(Search<BAccountR.bAccountID>),
new Type[]
{
typeof(BAccountR.acctCD),
typeof(BAccountR.acctName),
typeof(CustomerExt.usrDemoField),
typeof(Address.addressLine1),
typeof(Address.addressLine2),
typeof(Address.postalCode),
typeof(CustomerAttribute.Contact.phone1),
typeof(Address.city),
typeof(Address.countryID),
typeof(CustomerAttribute.Location.taxRegistrationID),
typeof(Customer.curyID),
typeof(CustomerAttribute.Contact.salutation),
typeof(Customer.customerClassID),
typeof(Customer.status)
},
Visibility = PXUIVisibility.SelectorVisible, DescriptionField = typeof(Customer.acctName), Filterable = true, TabOrder = 2)]
After publishing the customization, custom Demo Field should finally appear in the ARInvoice Customer selector:
To enable searching against a custom field inside the ARInvoice Customer selector, open Invoices and Memos screen in the Layout Editor and type UsrDemoField as the GridProperties.FastFilterFields property of the Customer selector:
I am trying to create a create combobox with performcallback, but I got the error. here this error "the model item passed into dictionary is of type 'system.Collections.Generic.Lost'1[System.String]', but this dix=ctionary requires a model item of type 'DIS_iDealer.Models.SalesMonitoringModel'"
I don't know which code exactly I need to paste but this is what I have:
view combobox :
#model DIS_iDealer.Models.SalesMonitoringModel
#Html.DevExpress().ComboBoxFor(m => m.mpmGroupLine.DESCRIPTION, settings =>
{
settings.Name = "Desc_ID_CB";
settings.Properties.IncrementalFilteringMode = IncrementalFilteringMode.Contains;
settings.Properties.DropDownStyle = DropDownStyle.DropDownList;
settings.CallbackRouteValues = new { Controller = "Report", Action = "cbPartialCategoryDetail" };
settings.Properties.CallbackPageSize = 50;
settings.Properties.ValueField = "DESCRIPTION";
settings.Properties.TextField = "DESCRIPTION";
settings.Width = 150;
settings.SelectedIndex = 0;
settings.Properties.ClientSideEvents.BeginCallback = "function(s,e){e.customArgs['group_Id'] = Category_Id_CB.GetValue()}";
settings.Properties.ValidationSettings.ErrorTextPosition = ErrorTextPosition.Right;
settings.Properties.ValidationSettings.ErrorDisplayMode = ErrorDisplayMode.ImageWithText;
settings.Properties.ValidationSettings.Display = Display.Dynamic;
}).BindList((List<string>)new DIS_iDealer.DataAccess.SalesMonitoringDAC().GetProductGroupDetail(Model.mpmGroupLine.GROUPID).ToList()).GetHtml()
controller :
namespace DIS_iDealer.Controllers
{
public class ReportController : BaseController
{
[HttpGet]
public ActionResult Report_SalesMonitoring_2()
{
SalesMonitoringModel mode = new SalesMonitoringModel();
//MPMPRODUCTGROUPLINE itemB = new MPMPRODUCTGROUPLINE();
/*List<string> mpmCate = mode.GetProductGroup();
if (mpmCate != null)
{
itemB.DESCRIPTION = mode.mpmGroupLine.DESCRIPTION;
}*/
ReportModels modelReport = new ReportModels();
if (TempData["ReportSalesMonitoring2"] != null)
{
modelReport = (ReportModels)TempData["ReportSalesMonitoring2"];
string reportParam = string.Empty;
foreach (string item in modelReport.ParameterReport)
{
reportParam += item;
}
ViewBag.IframeURL = modelReport.WebURL + reportParam;
}
return View(mode);
}
[ValidateInput(false)]
public ActionResult cbPartialCategoryDetail(string group_Id)
{
//SalesMonitoringModel model = new SalesMonitoringModel();
SalesMonitoringDAC model = new SalesMonitoringDAC();
List<string> itemDetail = model.GetProductGroupDetail(group_Id);
return PartialView("_cbPartialCategoryDetail", itemDetail);
}
}
}
Please let me know if you need more info. Thanks.
view code:
#using HRHPMVS.Models
#model HRHPMVS.ViewModel.NationalityVM
#{
ViewBag.Title = "list";
//Layout = "~/Views/Shared/OrangeHR.cshtml";
Layout = null;
}
<h1>Details</h1>
<div>
<h1>Details</h1>
<div>
#if (Model.NationalitiesList != null)
{
foreach (var item in Model.NationalitiesList)
{
#Html.DisplayFor(m => item.Code)
}
}
</div>
</div>
controller code:
public ActionResult list()
{
ModelState.Clear();
NationRepObj.list();
return View();
}
model:
namespace HRHPMVS.Models
{
public class Nationality
{
public int ID { get; set; }
[Display(Name = "Name")]
[Required(ErrorMessage = "Name is Requirde")]
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "please: Use letters only ")]
public string Name { get; set; }
[Display(Name = "Code")]
[Required(ErrorMessage = "Code is Requirde")]
[RegularExpression(#"[0-9]*\.?[0-9]+", ErrorMessage = "{0} must be a Number.")]
[Range(0, int.MaxValue, ErrorMessage = "Please: enter valid integer Number")]
public int Code { get; set; }
public Nullable<short> IsActive { get; set; }
// ...
}
}
viewmodel:
namespace HRHPMVS.ViewModel
{
public class NationalityVM
{
public Nationality Nationality { get; set; }
public List<Nationality> NationalitiesList { get; set; }
// ...
}
}
viewmodellist:
namespace HRHPMVS.ViewModel
{
public class NationalityVMList
{
public List<NationalityVM> Nationalities {get;set;}
// ...
}
}
function :
public void list()
{
List<Nationality> n = new List<Nationality>();
Nationality nt = new Nationality { Code=1,Name="doodoo",ID=1,IsActive=1};
NationalityVM vm = new NationalityVM ();
List<NationalityVM> l1 = new List<NationalityVM>();
// foreach(var itm in nt)
n.Add(nt);
if (vm.NationalitiesList == null)
{
vm.NationalitiesList = new List<Nationality>();
vm.NationalitiesList.Add(nt);
}
}
I am trying to view detailed nationality in a view. I want to view it from listviewmodel but I failed. I made the viewmodel list point to view model and view model point to model but when I am trying to add nationality to list in return null value with error Null reference exception wasn't handled in user code.
I want to display nationality detail from viewmodel list
There are several issues with this code that it is hard to know what you are trying to achieve.
You have a class dubbed 'viewmodellist' called NationalityVMList. I don't believe this has a purpose. Maybe delete it.
Your view expects a model of type NationalityVM but your controller action passes nothing to it.
Your 'function' creates a list along with several unused variables and returns nothing.
Change your controller so it passes a model to the view:
public ActionResult list()
{
NationalityVM model = NationRepObj.GetNationalityVM();
ModelState.Clear();
return View(model);
}
Change your function to:
public NationalityVM GetNationalityVM()
{
NationalityVM vm = new NationalityVM();
Nationality nt = new Nationality { Code=1,Name="doodoo",ID=1,IsActive=1};
vm.NationalitiesList = new List<Nationality>();
vm.Add(nt);
return vm;
}
Hopefully this will get something working.