I'm working on an ASP.Net core 3.1 MVC project in which I want to create a custom Validator, where shipped qty cannot exceed the ordered qty. I am getting a compile error in the model ([ValidShippedQty(Pending)]) in the ViewModel Error CS0120 An object reference is required for the non-static field, method, or property 'ShipmentsViewModel.Pending'
This is my ViewModel
public class ShipmentsViewModel
{
public string CustomerName { get; set; }
public int OrderID { get; set; }
public int LineItemID { get; set; }
public int Qty { get; set; }
public int ShippedQty { get; set; }
[System.ComponentModel.DefaultValue(0)]
public int Pending { get; set; }
[Required]
[Display(Name = "Ship Date")]
public DateTime thisShipDate { get; set; }
[Required]
[Display(Name = "Courier")]
public string thisCourier { get; set; }
[Required]
[Display(Name = "Qty Shipped")]
[ValidShippedQty(Pending)]
public int thisQty { get; set; }
public List<ShipmentDetails> shipmentDetails;
}
This is my custom validation attribute
public class ValidShippedQty: System.ComponentModel.DataAnnotations.ValidationAttribute
{
public int MaxValue { get; set; }
public ValidShippedQty(int MaximumQtyAllowed)
{
MaxValue = MaximumQtyAllowed;
}
public override bool IsValid(object value)
{
int intvalue = int.Parse(value.ToString());
bool retvalue;
if (intvalue > MaxValue)
retvalue = false;
else
retvalue = true;
return retvalue;
}
}
and the cstml page (part) is as follows
<div class="col-4">
<div class="form-group">
<label asp-for="@Model.thisQty" class="control-label"></label>
<input asp-for="@Model.thisQty" class="form-control" />
<span asp-validation-for="@Model.thisQty" class="text-danger"></span>
<input type="hidden" asp-for="@Model.LineItemID" />
</div>
</div>
An object reference is required for the nonstatic field, method, or property 'member'
In order to use a non-static field, method, or property, you must first create an object instance. For more information about static methods, see Static Classes and Static Class Members . For more information about creating instances of classes, see Instance Constructors .
Below are some causes and fixes for the above error.
first create an instance of the class.
CS0120 will also be generated if there is a call to a non-static method from a static method. To correct this error, first create an instance of the class.
a static method cannot call an instance method unless you explicitly give it an instance of the class. To correct this error, you could also add the keyword static to the method definition.
To get a detailed code example, please refer to Compiler Error CS0120
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.