Adding warehouse selector to the custom field in acumatica - selector

I created a custom field and trying to add the warehouse selector to it.I try to read from the customization guide and tried it but,the selector does not show up in the custom field.
This is the code I tried.
#region UsrCustomSite
[PXDBInt]
[PXUIField(DisplayName="Warehouse", Visibility = PXUIVisibility.SelectorVisible)]
[PXSelector(typeof(Search<IN.INSite.siteCD>),typeof(IN.INSite.descr),DescriptionField =(typeof(IN.INSite.siteCD)),SubstituteKey =(typeof(IN.INSite.siteCD)),DirtyRead =true)]
public virtual int? UsrCustomSite { get; set; }
public abstract class usrCustomSite : PX.Data.BQL.BqlInt.Field { }
#endregion
Am I missing something here?

I would try changing
[PXSelector(typeof(Search<IN.INSite.siteCD>)
to
[PXSelector(typeof(Search<IN.INSite.siteID>)
You are storing an int so you want the id, the substitute Key setting will make it so that the UI will show the CD.

Related

Instantiating ModelExpression directly

Let's say I have the following input tag which utilizes the built-in tag helper:
#model ProductViewModel
<label asp-for="Product.Id"></label>
In my case, this expands into the following:
<label for="Product_Id">Id</label>
I see that asp-for is expecting a ModelExpression:
In tag helper implementations, I often see a property like the following:
public ModelExpression For { get; set; }
It appears that this is automatically populated when the tag helper is used.
Is there a way to instantiate a ModelExpression directly in C#?
I.e. something like this:
var exp = new ModelExpression("Product.Id",...)
I'd like to be able to generate "Product_Id" and "Id" from Product.Id as the input tag helper did.
As far as I know, you can specify that your property is to be set to the name of some property on the View's Model object by declaring your property with the ModelExpression type. This will enable any developer using your property to get IntelliSense support for entering a property name from the Model object. More importantly, your code will be passed the value of that property through the ModelExpression's Model property.
Sample code as below:
[HtmlTargetElement("employee-details")]
public class EmployeeDetailTagHelper : TagHelper
{
[HtmlAttributeName("for-name")]
public ModelExpression EmployeeName { get; set; }
[HtmlAttributeName("for-designation")]
public ModelExpression Designation { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "EmployeeDetails";
output.TagMode = TagMode.StartTagAndEndTag;
var sb = new StringBuilder();
sb.AppendFormat("<span>Name: {0}</span> <br/>", this.EmployeeName.Model);
sb.AppendFormat("<span>Designation: {0}</span>", this.Designation.Model);
output.PreContent.SetHtmlContent(sb.ToString());
}
}
Code in the View page:
#model WebApplication7.Models.EmployeeViewModel
<div class="row">
<employee-details for-name="Name" for-designation="Designation"></employee-details>
</div>
Code in the Model
public class EmployeeViewModel
{
public string Name { get; set; }
public string Designation { get; set; }
}
From above code, you can see that we could custom the attribute name. More detail information about using the ModelExpression, check the following links:
Creating Custom Tag Helpers With ASP.NET Core MVC
Expression names
I'd like to be able to generate "Product_Id" and "Id" from Product.Id
as the input tag helper did.
Besides, do you mean you want to change the Product. Id to Product_Id, in my opinion, I'm not suggesting you change it, because generally we can use "_" as a separator in the property name. So, if we are using Product.Id, it means the Product's Id property, and the Product_Id means there have a Product_Id property.
To answer the question:
Is there a way to instantiate a ModelExpression directly in C#"
Yes you can, through IModelExpressionProvider and its CreateModelExpression method. You can get an instance of this interface through DI.
Now, if you're already in your view and working with tag helpers, Zhi Lv's answer is all you need, as the functionality is built-in and much easier to use. You only need IModelExpressionProvider for when you're in your Razor Page, Controller, or perhaps some custom middleware. Personally, I find this functionality useful for my Ajax handlers that need to return one of my ViewComponents that has a ModelExpression argument (so that I can easily call it from my Pages/Views too.)
To call CreateModelExpression, you'll need a strongly-typed instance of ViewData. In Razor Pages, this is as easy as casting the ViewData property to the strongly-typed instance of your PageModel's type (presuming you don't have a page model hierarchy):
var viewData = (ViewDataDictionary<IndexModel>)ViewData;
If you're using MVC and you're in the controller, that won't exist yet. Best you can do is make your own instance.
var viewData = new ViewDataDictionary<ErrorViewModel>(new EmptyModelMetadataProvider(),
new ModelStateDictionary());
Once you get your strongly-typed ViewData instance, you can obtain your desired ModelExpression like this, just like using a lambda expression in your views:
var myPropertyEx = _modelExpressionProvider.CreateModelExpression(viewData,
m => m.MyProperty);

Should I have both text and value in my model for a property that is selected from dropdownlist

In ASP.NET MVC application I have a model named CarSearchCriteria:
public class CarSearchCriteria{
public int CarMake {get;set;} // This is selected from a dropdownlist
public int YearOfFirstReg {get;set;}
public string ModelVariant {get;set}
}
I have two views - one for editing and the other one for viewing. In the editing view for the CarMake property I can do the following. I know I could have used DropDownListFor but didn't want to mess with SelectList for the time being:
<select name="CarMake">
<option value="1">BMW</option>
<option value="2">Mercedes</option>
<option value="3">Toyota</option>
</select>
So the model binding mechanism will easily bind the selected value to the appropriate model property. But what about the reading mode. I can't show 1s or 2s. I need to show BMW, Mercedes and so on. My question is what is the preferred way, do I have to have a property name that holds the actual textual information, something like CarMakeText?
You could have both the identifier (which you currently have) as well as the Make object itself. The latter would never need to be accessed when building the model, but can be accessed when reading the model. A lazy-loaded read-only property often works well for that. Something like this:
public int CarMakeID { get; set; }
public Make CarMake
{
get
{
if (CarMakeID == default(int))
return null;
// fetch the Make from data and return it
}
}
Naturally, this depends a lot on what a Make actually is and where you get it. If there's just some in-memory list somewhere then that should work fine. If fetching an instance of a Make is a little more of an operation (say, fetching from a database) then maybe some in-object caching would be in order in case you need to access it more than once:
public int CarMakeID { get; set; }
private Make _carMake;
public Make CarMake
{
get
{
if (CarMakeID == default(int))
return null;
if (_carMake == null)
// fetch the Make from data and save it to _carMake
return _carMake;
}
}
David's solution is just fine but for some reason I find my own solution to better fit my needs and besides that I find it more elegant. So basically what I do is I create a class that holds the textual descriptions of all the properties that keep just ID. For example, I have the following model:
public class EmployeeModel{
public int EmployeeID {get;set;}
public string FullName {get;set}
*public int DepartmentID {get;set}
*public int SpecialityID {get;set;}
public int Age {get;set;}
}
The properties marked with asterisk are the properties that keep ids of possible many predefined options and when showing we're supposed to show the actual descriptions, not the number representations. So for this purpose, we create a separate class:
public class EmployeeTextValues{
public string DepartmentName {get;set;}
public string SpecialityName {get;set;}
}
And then I just add this class as a property to my model:
public EmployeeTextValues TextValues {get;set;}
After that, it's quite easy to access it from anywhere, including Razor.
P.S. I'm sure that a lot of people will tend to do the following before initializing this property:
Employee emp=new Employee;
emp.Age=25;
emp.TextValues.DepartmentName="Engineering";// Don't do this
If you try to access or set Textvalues.Someproperty you'll get Object reference not set to an instance of an object. So do not forget to set TextValues first to some initialized object. Just a kind reminder, that's all.

MVC 4 Validation Attribute is not working for dynamically added fields

Here are my Product and ProductItem classes/models:
public class Product
{
public int ProductId { get; set; }
[Required(ErrorMessage="Enter Name")]
public string Name { get; set; }
public List<ProductItem> productitems { get; set; }
[Required(ErrorMessage="Enter Price")]
public decimal Price { get; set; }
}
public class ProductItem
{
[Required(ErrorMessage="Select Raw Material")]
public int RawMaterial { get; set; }
[Required(ErrorMessage="Enter Quantity")]
public decimal Qty { get; set; }
}
For ProductItem I am adding its fields dynamically with jQuery, as you can see here:
$("#btnAddProductItem").click(function () {
$.getJSON("/rawmaterial/GetRawMaterials", null, function (data) {
var productItem = $("<tr class='productItem' id='productItem-0'><td><select id='rmlist-0' name='productitems[0].RawMaterial'></select><span class='field-validation-valid' data-valmsg-for='productitems[0].RawMaterial' data-valmsg-replace='true'></span></td><td><input type='text' id='rmqty-0' name='productitems[0].Qty'/><span class='field-validation-valid' data-valmsg-for='productitems[0].Qty' data-valmsg-replace='true'></span></td></tr>");
$("#productItem").append(productItem);
$("#rmlist-0").addItems(data);
});
});
Now the validation attributes applied on Name and Price are working fine but not on the fields added dynamically (i.e. "RawMaterial" and "Qty").
Please give me the suggestions how this validation will work ?
Note: For testing purpose I have just added the first object of the List indexed with 0.
There are several ways to accomplish this -
PARTIAL VIEW: Since you are using Server Side data annotation as I see from the class definitions, then it is not a good idea to load dynamically with js. Because you will miss out all the validation that MVC 4 could have created automatically. So, the best solution I would suggest is taking the code that you are adding dynamically to a partial view file and then get the html with ajax call and then populating the HTML.
JS VALIDATION: But, if it is a must that you should use JS, then you have to add all the validation items yourself. To do that you have to do some extra works -
First, inspect the HTML with any developer tools, you will notice that there is a <span> attribute appended after each item to show the error which has a target mentioned. You have to append similar attributes to your elements
With MVC 4 unobtrusive validation, all the validation attributes and rules are added with the target element with data attributes. Each one is based one the validation they stands for. You have you create attributes similar to that.
Finally, after adding all the validation items in JS, reset the form so that it parses the new validations added and work accordingly. The code to parse the validations are here -
var form = $("form") //use more specific selector if you like
form.removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
But I would prefer the partial view solution, since it will require least amount of re-work and also gives you option to keep all your validation in one place. You don't have to worry about new validations to be ported to js in future.

How to hide a Model class field based on custom logic in MVC Web Api RC

I am using Asp.Net Mvc Web api RC.
I wanted to hide the fields/properties of my model class using custom attribute. Below is my class:
public class Employee
{
public int EmpId { get; set; }
public string Name{ get; set; }
//Wanted to hide this attribute based on custom logic. Like for a certain role, i want to hide the designation
public string Designation{ get; set; }
public string Department{ get; set; }
}
How can we achieve using Data Annotations. I mean i wanted to create a separate attribute to use in this manner:
[HideForRoles(Roles="Admin,Writer")]
public string Designation{ get; set; }
UPDATE :
As i am developing web api. The response is serialized to either XML or Json format depend upon the formatter. So better question would be how not to allow the fields to be serialize while writing to the response.
However one option could be using IgnoreDataMember attribute. Like
[IgnoreDataMember]
public string Designation{ get; set; }
But the above is a compile time declaration where i cannot impose any condition.
Question: How to ignore the field/property while serializing based on some condition at runtime?
Totally missed on the first go-round that you were using Web Api, my apologies.
What you want to do is to create a custom formatter.
There's a good article here on the flow/differences between MVC and Web Api (which I'm getting that you already understand, still some valid points here):
http://lostechies.com/jimmybogard/2012/04/10/asp-net-web-api-mvc-viewmodels-and-formatters/
And here's a sample implementation of a custom formatter:
http://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format
Building from that, you would use reflection to read from the attributes, building on the custom ActionFilterAttribute you would have to write, where you evaluate the user's roles and determine which fields should be omitted/included. Here's a sample of an action filter:
https://github.com/MisterJames/MovieFu/blob/master/MovieFu/ActionFilters/UserNameFilter.cs
Hope this helps more.
Cheers.
Your best bet is to return a dynamic object. In this case you can say:
dynamic viewModel = new ExpandoObject();
viewModel.Id = 12;
if(role == "Admin")
{
viewModel.SecureStuff = "Others should not see it";
}
It won't be as straightforward as that, as you'll need to have the fields conditionally rendering in the view. But you can get most of the way there through the attribute.
You will need to make your custom attribute meta-data aware, then check the attribute in your view. A solution is posted here: Can't get Custom Attribute Value in MVC3 HTML Helper.
Cheers.
I have done the authorization checking in the model repository itself. Rather ideal way was to create custom formatters for hiding the certain fields based on some condition.
After getting the list of Employees from db and have them in list, i iterated again and place a NULL to the fields i don't want to display.
The code i have written as:
foreach (var employee in listEmployees)
{
//get all props. of Employees object using reflection
var props = employee .GetType().GetProperties();
//loop through each field to match with the field name to remove/place null
foreach (var propertyInfo in props)
{
var fieldName = propertyInfo.Name;
if (fieldsNamesToRemove .Contains(fieldName))
{
propertyInfo.SetValue(employee , null, null);
}
}
}
here fieldsNamesToRemove is a list that i created dynamically based on roles of current user.
This solution actually placing a NULL for the fields we do not want display. As a result in JSon format the fields are not displaying but in the XML the fields are displaying with syntax like lt; Designation i:nil="true"/ gt;, but manageable as we need to deal mostly with json response.
Thanks Ali and MisterJames for your valuable suggestions

MVVM Silverlight - can not assign existing control to a property of collection of custom elements in XAML

I have a class
public class Item
{
public string A { get; set; }
public Control B { get; set; }
}
I'm using MVVM with Silverlight. I have a custom view that is inherited from a standard view. Custom view has public property public ICollection MyItems { get; set; } which should store items described above.
In xaml of my view I have
xxxx.MyItems>
Item A="someText" B="_existingButton" />
Item A="someText2" B="_existingButton2" />
/xxxx.MyItems>
Initialize() method of View fails when trying to assign value for B.
How can I assign a reference to existing element for a custom collection item?
I don't exactly understand what you are trying to achieve, but to help you arrive at a solution, I recommend that you attempt your task in the code behind file first (i.e. in the .xaml.cs) file.
By doing this, you will be given much more informative help from the compiler and intellisense.
Once you've achieved what you wanted in the code behind, then try and implement it in the xaml file.