I am using Asp.net MVC 4 and .NET 4.5. I have a table with one column which is decimal not null value. I have created a razor view using scaffolding template of MVC for model that is created by Entity framework for that table.
Now when we enter 0 or nothing(null) on text box of decimal property, on server it is coming as 0. and after validation it displays as zero on text box.
is there any way using which we can identify whether client has entered zero or null on text box so that after post back, if any validation comes, client gets the value which he/she has posted
Update 1
public partial class Student
{
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public System.DateTime EnrollmentDate { get; set; }
public decimal RollNo { get; set; }
}
is the class that EF has generated.
and in View I have used
@Html.TextBox("Students[0].RollNo", Model.Students[0].RollNo)
in my model, this list of this class is a property.
I would recommend using a custom validation attribute as descriped here: ASP.NET MVC: Custom Validation by Data Annonation
public class MyAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
int temp;
if (!Int32.TryParse(value.ToString(), out temp))
return false;
return true;
}
}
and decorate your property with [MyAttribute]
EDIT:
As the empty textbox provides a zero on empty just change your property to a nullable one double?. This should submit a null which can be separated from zero.
public partial class Student
{
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public System.DateTime EnrollmentDate { get; set; }
public decimal? RollNo { get; set; }
}
MSDN Nullable Types
Edit 2:
As you have no influencs on the model and don't want to use viewmodels and backupproperties, here's another approach : using a custom modelbinder.
public class DoubleModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (string.IsNullOrEmpty(valueResult.AttemptedValue))
{
return double.NaN;
}
return valueResult;
}
}
protected void Application_Start()
{
ModelBinders.Binders.Add(typeof(double), new DoubleModelBinder());
}
That gives you the constant double.NaN value in your model, if the submitted value is empty. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With