Remove default value for non nullable properties when using EditFor [asp.net mvc 3] - asp.net-mvc-3

How can I remove the default value that is added by default to the textboxes of non nullable properties when using the EditFor helper? I don't want that behavior
EDIT
Sorry I didn't give enough information.
For example if you use Html.EditorFor with a property that is DateTime it will set the textbox value to 1/1/0001 automatically. If you use "DateTime?"(nullable), it won't, it just leaves the textbox empty.

You can use UIHint to do it.
Create a file called ShortDate.cshtml in EditorTemplates
#model DateTime
#{ var value = Model == default(DateTime) ? null : Model.ToShortDateString(); }
#Html.TextBox(string.Empty, value)
Decorate your property with the UIHintAttribute referencing our EditorTemplate. Consider my Order class.
public class Order {
[UIHint("ShortDate")]
public DateTime Date { get; set; }
}
When you use
#Html.EditorFor(x => x.Date)
it should avoid the default value of DateTime
caveat: I just did simple tests, so please take a deep look into it.
hope it helps you

I had to do something like this for my own needs. I used this:
#model DateTime?
#Html.TextBox("", (Model.Value != default(DateTime) ? Model.Value.ToShortDateString() : string.Empty))
and it worked pretty nicely for my DateTime values. Ones that didn't have the default value are blank and the ones that have some other DateTime value show the ShortDateString representation of the object.

Related

ASP.NET MVC 4 avoid generation of data-val-date for datetime

how can I avoid the generation of the html attribute "data-val-date" for the element created from a Datetime property?
The model:
public class RegisterModel
{
[Required]
[Display(Name = "Date of birth")]
public DateTime? DateOfBirth { get; set; }
}
The view:
#Html.LabelFor(m => m.DateOfBirth)
#Html.EditorFor(m => m.DateOfBirth)
In fact, I'm creating a three drop down lists element for selecting the date of birth, which don't give a value in a date format.
Some solutions I've seen, consisted in a work around: removing the validation with a javascript.
The solution I envisage is to split the DateTime property into three long one for each value (day, month, year).
Ok, this took me an afternoon of work... apparently mvc4 decided that it was time to render a data-val-date="Message" on EVERY datetime property on the viewmodel. I've tried to modify this default behaviour but didn't succeed.
This solved my problems:
$.validator.addMethod('date',
function (value, element) {
return true; // since MVC4 data-val-date is put on EVERY vm date property. Default implementation does not allow for multiple cultures...
});
You can also try to write your own editor template named "DateTime.cshtml" in your shared EditorFor folder, but don't use TextBoxFor there, because that one is polluted as well.
data-val-date is used by the validation system to validate the date. If you remove it, client-side validation won't work.
If that's what you want, then just disable client-side validation.
Add this to your application start in your global.asax file and the form should fire.
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Automatical bind of datetime fields in MVC3

I have a page with many date fields, which can be dynamically added on client side. I have a DatTime? property on editor template for this field:
[Display(Name = "Bar Admission Date")]
public DateTime? AdmissionDate { get; set; }
When I'm submitting a form I get a null data in AdmissionDate field because binder doesn't know the format of the field.
I have 2 ideas of how t oovercome this issue:
Make a string field in model and parse it on a server side. Simple and pretty quick.
Write a custom model binder for date fields. I don't like this solution because I don't know the keys for all fields that I will use.
Is there better solution? I searched how can I overload TextboxFor method in order to pass it a culture, but I didn't find
Sounds like you should use an enumerable (IList/ICollection) of DateTime?. Phil Haacked has a good article on model binding to a list (even when the number of items is dynamic).
Updated
As for the formatting problem, I would look at how to set the culture for the project/model binder.

Html.EditorFor nullable DateTime posting back as null from view

Lets make the following assumptions; ASP.NET MVC 3 Razor C#, a strongly typed view bound to a view model (not entities etc.), using the Html.EditorFor method, to edit a nullable DateTime property in the view model. The two data annotation attributes I added seem to be causing model binding to fail.
Sample view code
#model MyApp.ViewModels.NullableDateTimeViewModel
#using (Html.BeginForm())
{
#Html.EditorFor(m => m.DateOfBirth)
}
Sample ViewModel code
[DataType(DataType.Date,
ErrorMessage = "Please enter a valid date in the format dd MMM yyyy")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
public class NullableDateTimeViewModel
{
public DateTime? DateOfBirth { get; set; }
}
Sample controller code
[HttpPost]
public ViewResult DoB(NullableDateTimeViewModel nullableDateTimeVM)
{
ContextDB db = new ContextDB();
Customer cust = new Customer();
// DateOfBirth is null so the update fails
cust.DateOfBirth = nullableDateTimeVM.DateOfBirth.Value;
db.Customers.Add(cust);
db.SaveChanges();
}
The data entered in the view is not posting back to the controller when the form in the view is submitted when the data annotation attributes are added. This means that model binding is failing when using EditorFor with those attributes. Model binding works fine with TextBoxFor, the value entered in the TextBoxFor input box is passed back to the view with the view model. What is the problem here with EditorFor and the data annotation validation attributes?
Can we please find a solution that does not involved reinventing the wheel by creating multiple additional classes, helpers, templates and writing a whole lot of additional code? I am looking for a one or two line solution.

MVC3 Required validation, choose value for empty

I have a hidden field which is bound to a int Id in the model, it has a required attribute and some fancy ajax code to set the id client side, the problem is that zero should be acounted as empty. Now the validation will succeed even if no Id has been selected, bow can I set which value should be counted as empty? I hope i do not need to create a custom validator for it.
Thanks
It doesn't maker sense to add required attribute to a non nullable type such as Int32. Value types are always required. You could use a nullable integer instead:
[Required]
public int? SomeProperty { get; set; }

Razor: #Html.HiddenFor() need to turn off validation

Could you help me, please.
I have a class:
public class Product
{
...
// NOT REQUIRED!
public virtual Category Category{ get; set; }
}
But when in a view I create
#Html.HiddenFor(model => model.Category.Id), or
#Html.Hidden("model.Category.Id", model => model.Category.Id)
razor adds validation attribute to this.
How to turn it off? (in model, in view)
How to turn off validation event if a property has the attribute [Required]?
I found out that this is not a razor problem, it is somewhere in MVC.
Even if I manage to pass "Category.Id" value = "" to the server, TryModelUpdate() will fail - it requires "Category.Id" to be set, but it's not required in my model.
Why is it so??!
I solved the same issue with an crutch like this:
#{ Html.EnableUnobtrusiveJavaScript(false); }
#Html.HiddenFor(t => t.Prop1)
#Html.HiddenFor(t => t.Prop2)
...
#{ Html.EnableUnobtrusiveJavaScript(true); }
Setup a hidden like:
#Html.Hidden("CategoryIdHidden", model => model.Category.Id)
And process the posted hidden value separate from the model binding stuff... I think the validation is UI specific, and not model specific, so it wouldn't validate the category ID.
Or, supply in the hidden a default value of "0". A value of "" probably won't evaluate correctly if the category.ID is of type int, hence its null, hence it errors.
HTH.

Resources