mvc data annotation validator for datetime always shows required - asp.net-mvc

when I submit my form, Termination date field shows "Termination Date field is required" even though I haven't defined it as required anywhere.
my model is defined as:
[Display(Name = "Termination Date")]
public DateTime TerminationDate { get; set; }
razor code is:
<div class="col-md-6 form-group">
#Html.LabelFor(model => model.Posting.TerminationDate)
#Html.TextBoxFor(model => model.Posting.TerminationDate, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Posting.TerminationDate)
</div>
I do not want any type of validation on this field. How can I do that?

Make the property nullable
DateTime? or Nullable<DateTime>
Or reconfigure the convention
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

Related

How to set value to a field in mongodb without using the field in view form

I want to set a value to Status property without using it in the view form
Here is the model class
public class NewsLetterModels
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[Required]
public string NewsLetterName { get; set; }
[Required]
[DataType(DataType.EmailAddress, ErrorMessage = "E-mail is not valid")]
public string AssigneeEmailId { get; set; }
public string Status { get; set; }
public NewsLetterModels()
{
}
public NewsLetterModels(PostNewsLetter postNewsLetter)
{
NewsLetterName = postNewsLetter.NewsLetterName;
AssigneeEmailId = postNewsLetter.AssigneeEmailId;
Status = postNewsLetter.Status;
}
}
I don't want to set value to the field in viewform.In fact I don't want to show this field in the viewform. when I click on initiate News Letter,"Initiated" value should be set to the propert "Status". I am using MongoDb as database
Here is the View Page
<fieldset>
<legend>PostNewsLetter</legend>
<div class="editor-label">
#Html.LabelFor(model => model.NewsLetterName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.NewsLetterName)
#Html.ValidationMessageFor(model => model.NewsLetterName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AssigneeEmailId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssigneeEmailId)
#Html.ValidationMessageFor(model => model.AssigneeEmailId)
</div>
<p>
<input type="submit" value="Initiate NewsLetter" />
</p>
</fieldset>
Any help will be appreciable.
Are you referring to the 'Status' property?
You should set this in the controller or if you are using a repository layer you could in a save method insert values before saving to database.

ASP.NET MVC Razor - All form fields are required?

I have a form that is generated by ASP.NET.
I have some required fields, and I am using the [Required] dataAnnotation for that.
However, the elements that don't have the [Required] DataAnnotation are also required according to my webpage. These are not required at all yet I cannot submit the form if they are empty.
I used scaffolding to make the pages, jquery validator is used (by default) for the validation.
Model class (some fields have been omitted for clarity)
public class Room
{
[Key]
public int ID { get; set; }
[Required(ErrorMessage = "Please enter the minimum (default) price for this room.")]
[DataType(DataType.Currency)]
[Display(Name = "Minimum price")]
public decimal MinPrice { get; set; }
[Display(Name = "Alternative price")]
[DataType(DataType.Currency)]
public decimal AltPrice { get; set; }
}
The code that creates the form fields in de .cshtml file:
<div class="form-group">
#Html.LabelFor(model => model.MinPrice, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MinPrice)
#Html.ValidationMessageFor(model => model.MinPrice)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AltPrice, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AltPrice)
#Html.ValidationMessageFor(model => model.AltPrice)
</div>
</div>
The required field correctly displays the error message as defined (thus it reads the annotations).
The non required field displays a generic error message instead ("The Alternative price field is required.").
I've searched quite a lot, but everywhere it says that if the [Required] DataAnnotation is not there, it won't be required in the form.
Make the non-required fields nullable.
I was having the same problem. I had to go into my model and put ? marks in the int fields to make them null. The fields that were set as string were fine it was just the int fields that were causing the issue.

How to turn off MVC form validation

I have a data-first set-up so my models are generated by the entity framework from my database and there is no default [Required] annotations. I have a simple table with three fields. One ID and two VARCHAR / text based fields.
No matter what I try, I cannot get the CRUD forms to stop validation. I disabled in the Web.config, I add [ValidateInput(false)] to the Create() method in the controller, but has no effect. I set the #Html.ValidationSummary to false,
This is the basic view:
#using (Html.BeginForm()) {
#Html.ValidationSummary(false)
<fieldset>
<legend>CallType</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CALLTYPE)
</div>
<div class="editor-field">
#Html.TextBox("calltype", "", new { style = "width: 50px;" })
#Html.ValidationMessageFor(model => model.CALLTYPE)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DESCRIPTION)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DESCRIPTION)
#Html.ValidationMessageFor(model => model.DESCRIPTION)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Model (generated by Framework):
public partial class CALLTYPES2
{
public int ID { get; set; }
public string CALLTYPE { get; set; }
public string DESCRIPTION { get; set; }
}
Even if I insert just one character in each field, it still says: "The Value 'x' is invalid"
(I leave the validation messages on so I can see what is going on.)
What am I supposed to do? And how would I validate these fields later on - can I just add [Required] to Model generated code? What if I regenerate the Model from the database?
Does this have something to do with the model state in the controller?
[HttpPost]
public ActionResult Create(CALLTYPES2 calltype)
{
if (ModelState.IsValid)
{
db.CALLTYPES2.Add(calltype);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(calltype);
}
Not sure what I am missing and the tutorials I have read do not shed much light. Thanks for your response and apologies for my ignorance.
UPDATE
Found my error - The object name "calltype" in the Method Create() is the same as the name/id of the form field "calltype". I guess the binder tries to bind the string "calltype" to the object "calltype". Renamed it to:
public ActionResult Create(CALLTYPES2 ctype)
Now it works in both the Edit and Create Windows. "ctype" is not clashing with "calltype".
You forgot to include the ID field in your form. You could include it as a hidden field:
#Html.HiddenFor(model => model.ID)
Now the value of the ID property will be sent to the server when the form is submitted and the default model binder should not complain.

Disable validation on a #Html.TextBox in MVC

I have a form in which I want to disable the required validation on one of the #Html.TextBox elements. The front end is as follows:
#model Models.NewUser
#using (Html.BeginForm("Register", "Account"))
{
<div class="field">
<span class="textOverField absolute em1-2" style="top:6px;left:4px;">Key</span>
#Html.TextBox("SchoolGroupKey", "", new { #class = "textField" })
</div>
<div class="field">
<span class="textOverField absolute em1-2" style="top:6px;left:4px;">Name</span>
#Html.TextBox("Names", "", new { #class = "textField" }) <div class="absolute validationMessage">#Html.ValidationMessageFor(u => u.Names)</div>
</div>
<div class="field">
<span class="textOverField absolute em1-2" style="top:6px;left:4px;">Last Name</span>
#Html.TextBox("LastNames", "", new { #class = "textField" }) <div class="absolute validationMessage">#Html.ValidationMessageFor(u => u.LastNames)</div>
</div>
<div class="em0-9" style="margin-bottom:20px;">
<input class="submitButton cursorHand" style="margin-top:10px;" type="submit" value="Registrarme" />
</div>
}
And the code for the model is as follows:
public class NewUser
{
[Required(ErrorMessage = "Name required")]
public string Names { get; set; }
[Required(ErrorMessage = "Last name required")]
public string LastNames { get; set; }
public System.Guid SchoolGroupKey { get; set; }
}
I'm guessing that the #Html.TextBox has a default validation even though I don't specify it. Is there someway to remove it?, I tried removing the html tags data-val-required and data-val, but still no results.
Thanks
Guid is a structure that behave as a simple type (just like int or DateTime). As such it is automaticly validated. If you want to make a workaround change your property type from Guid to nullable Guid?. Example:
public System.Guid? SchoolGroupKey { get; set; }
Of course you will have to change places when you use this property, to access the guid value throught Value property of nullable type.
If the mapping fails you will not get any validation errors then - just null value inside of your SchoolGroupKey property.

Unobtrusive javascript adding data to #Html.HiddenFor

I have a hidden field on a form that is created in Razor using the #Html.HiddenFor helper:
#Html.HiddenFor(model => model.BidID, new { id="bidItemID" })
My View model looks like this:
public class BidEditVM
{
[Display(Name = "Bid ID")]
public int BidID { get; set; }
[StringLength(51)]
[Display(Name = "Customer Name")]
public string CustomerName { get; set; }
[StringLength(75)]
[Display(Name = "Bid Name")]
public string BidName { get; set; }
[Display(Name = "Amount")]
public decimal Amount { get; set; }
[Display(Name = "Time")]
public DateTime BidTime { get; set; }
}
When the HTML is rendered, unobtrusive javascript adds it's stuff to the hidden input field even though it will never require validation:
<input id="bidItemID" type="hidden" value="5198" name="BidID" data-val-required="The Bid ID field is required." data-val-number="The field Bid ID must be a number." data-val="true">
What's odder is that the message and validation it adds aren't even part of the view model for this partial view. The view looks like this:
#model AuctionAdmin.Models.ViewModels.BidEditVM
#using (Ajax.BeginForm("UpdateBid", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "modalBidInfo" }))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.BidID, new { id="bidItemID" })
<fieldset>
<legend>Edit Bid</legend>
<div class="display-label">#Html.LabelFor(model => model.CustomerName)</div>
<div class="display-field">
#Html.DisplayFor(model => model.CustomerName)
</div>
<div class="display-label">#Html.LabelFor(model => model.BidName)</div>
<div class="display-field">
#Html.DisplayFor(model => model.BidName)
</div>
<div class="editor-label">#Html.LabelFor(model => model.Amount)</div>
<div class="editor-field">
#Html.EditorFor(model => model.Amount)
</div>
<div class="editor-label">#Html.LabelFor(model => model.BidTime)</div>
<div class="editor-field">
#Html.EditorFor(model => model.BidTime)
</div>
</fieldset>
}
Where is it getting this metadata from and how can I stop it?
It's marked as such since the type in the view model is an int.
It's adding the html due to this line:
#Html.HiddenFor(model => model.BidID, new { id="bidItemID" })
Why is it a problem that the extra attributes are present?
If it really is problematic, try changing the type of BidId to int? (a nullable int).

Resources