i just wanted to know how to enable client side validations for dropdowns in asp.net mvc 2.
The scenario would be that the dropdown will contain a "Select" item and the list of other items..,The user should select other items... the validation should fire when the user does not select the other items
public class FacilityBulletinModel
{
[DisplayName("Select a Facility")]
public List<SelectListItem> ListFacility { get; set; }
[DisplayName("Facility Bulletin")]
[Required(ErrorMessage = "Please create a Bulletin")]
public string FacilityBulletin { get; set; }
[DisplayName("Active")]
public bool Active { get; set; }
[HiddenInput(DisplayValue = false)]
public int SiteId { get;set;}
}
in my view
Select Facility <span class="err">*</span><br />
<%=Html.DropDownListFor(model => model.ListFacility, null, new {onChange="updateSiteId()" })%>
<span class="err"> <%= Html.ValidationMessageFor(model => model.ListFacility) %></span>
First, if a dropdown is required, add the [Required] attribute to your model property.
Then, enable client side validation somewhere at the top of your view:
<% Html.EnableClientValidation() %>
Then just add a validation message:
<div class="inputField">
<%= Html.LabelFor(model => model.property)%>
<%= Html.DropDownListFor(model => model.property, (SelectList)ViewData["myselelectlist"])%>
<%= Html.ValidationMessageFor(model => model.property)%>
</div>
(this requries MicrosoftMvcValidation.js to be loaded)
Related
I am using [Required] for field validation. Scenario is, there are two check boxes and based on one selection, user has to add value in textbox. If it is empty then show validation error. Issue is, it validates it for first time, but shows validation message on both check box selection afterwards. What am I missing here?
Model:
[DisplayName("Flat Fee Amount")]
[Required(ErrorMessage = "Enter flat fee amount.")]
public string FlatFeeAmount { get; set; }
View:
<div id="show-delivery-fee">
<div>
<%= Html.RadioButtonFor(m => m.DeliveryFee, "All", new {id = "All"}) %>
<%= Html.Label("All", new {#for = "All"}) %>
</div>
<div>
<%-- BASED ON THIS CHECKBOX SELECTION DISPLAY VALIDATION MESSAGE--%>
<%= Html.RadioButtonFor(m => m.DeliveryFee, "FlatFee", new {id = "FlatFee"}) %>
<%= Html.Label("Flat Fee", new {#for = "FlatFee"}) %>
</div>
<div>
<%= Html.LabelFor(m => m.FlatFeeAmount) %>
<%= Html.TextBoxFor(m => m.FlatFeeAmount, new {maxlength = "5"}) %>
<%= Html.ValidationMessageFor(m => m.FlatFeeAmount)%>
</div>
</div>
Controller:
[HttpPost]
[RequiredAccessRights(AllowRightsOr = new[] { SystemRight.EditDelivery })]
[AuditActionFilter("Save store delivery. Store id: {model.StoreId.Value}")]
public ActionResult Delivery(StoreDeliveryModel model)
{
if(this.ModelState.IsValid)
{
try
{
this.StoreManager.SaveDeliveryModel(model);
model.Submitted = true;
}
catch (ValidationException exc)
{
this.ModelState.AddModelError("", exc.Message);
}
}
return View(model);
}
Output:
I got my desired output if I use RequiredIf annotation in model.
Model:
[DisplayName("Flat Fee Amount")]
[RequiredIf("DeliveryFee", "FlatFee", ErrorMessage = "Please enter flat fee amount.")]
public string FlatFeeAmount { get; set; }
I'm developing an MVC 5 web application. Within a particular View I need to validate a ViewModel, however, I need some of the validation only to occur depending on the users inpupt.
For example, I have a ViewModel
public class TimeEntryViewModel
{
public int proposalID { get; set; }
public int proposalCode { get; set; }
public int nonchargeCode { get; set; }
public SelectList UserProposals { get; set; }
public SelectList TimeEntryClientCodes { get; set; }
public SelectList TimeEntryNonChargeCodes { get; set; }
}
This ViewModel is passed to a View which looks like this
<div class="form-group">
#Html.LabelFor(m => m.proposalID, "Proposal")
#Html.DropDownListFor(m => m.proposalID, Model.UserProposals, "No Proposal", new { #class = "form-control"})
#Html.ValidationMessageFor(m => m.proposalID)
</div>
<div id="ClientCodes" class="form-group" style="display:none">
#Html.LabelFor(m => m.proposalCode, "Client")
#Html.DropDownListFor(m => m.proposalCode, Model.TimeEntryClientCodes, "Select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.proposalCode)
</div>
<div id="NonChargeCodes" class="form-group">
#Html.LabelFor(m => m.nonchargeCode, "Non Charge")
#Html.DropDownListFor(m => m.nonchargeCode, Model.TimeEntryNonChargeCodes, "Select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.nonchargeCode)
</div>
If the user selects 'No Proposal' from the first drop down list, then the drop down list 'nonchargeCode' appears and I need to validate so that the user selects an option from it.
However, if the user selects another option from the first down drop list, then the drop down list 'nonchargeCode' will disappear and another drop down called 'proposalCode' will appear. I then want to validate to ensure the user selects an option from this drop down, but not the 'nonchargeCode' (which will be hidden).
In an MVC 4 application I previously coded, I used http://fluentvalidation.codeplex.com/ to help with this scenario.
I'm just wondering if anyone else had used anything else to overcome this problem of conditional validation? If so, I'd be keen to hear.
Thanks again.
You can use conditional validation in jQuery and in fluentvalidation.
You can use a jQuery selector on the validation, something like this.
I'm not sure about the HTML element names.
$( "#myform" ).validate({ rules: {
proposalCode: {
required: "#proposalCode:visible"
} }
Check out jQuery Dependency expression for more information.
In FluentValidation validation (Server side only) you can use the 'When' expression.
RuleFor(r => r.proposalCode).NotNull().When(e => // Check selected value);
Check out the documentation here
I think this should get you started.
I am making my first tentative steps into MVC3 and have come across an issue with the translation of navigation properties within a model to a view. It seems that in the view navigational properties do not allow client side validation nor is the "Display" label attribute picked up.
I have the following simple model:
public class Entity
{
[Key,
ScaffoldColumn(false)]
public int Entity_Id { get; set; }
[Display(Name = "Entity Name"),
Required(ErrorMessage = "Please enter the entity name."),
StringLength(150, ErrorMessage = "Please ensure that the entity name is under 150 characters.")]
public string Entity_Nm { get; set; }
[Display(Name = "Entity Type"),
Required(ErrorMessage="Please select the entity type"),
ForeignKey("EntityType")]
public int EntityType_Id { get; set; }
public virtual EntityType EntityType { get; set; }
}
Which references this model:
public class EntityType
{
[Key]
public int EntityType_Id { get; set; }
[Display(Name = "Entity Name"), Required(ErrorMessage="Please enter the entity type name.")]
public string EntityType_Nm { get; set; }
}
When I create a controller with read/write actions and views for this model I get the following create form:
<fieldset>
<legend>Entity</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Entity_Nm)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Entity_Nm)
#Html.ValidationMessageFor(model => model.Entity_Nm)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EntityType_Id, "EntityType")
</div>
<div class="editor-field">
#Html.DropDownList("EntityType_Id", String.Empty)
#Html.ValidationMessageFor(model => model.EntityType_Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
This is fine apart from the label for the Entity Type drop down, for some reason it is not picking up the "Display" attribute of the navigation property within the model (note the lack of a space). Also client side validation is not enabled for the dropdown list (server side validation works without issue) despite decorating the property with a "Required" attribute. Client side validation works on the other fields. Please note that all the required .js script files have been included and I have also added the relevant enable validation keys to the web.config.
Any ideas what I am missing here? Thanks one and all.
for DropDownList Display issue just try below
#Html.LabelFor(model => model.EntityType_Id)
I'm testing my view/edit model's Data Annotations, and some of the errors aren't showing up. They're all property-level, but they're not showing up as either property-level or model-level. They're simply not showing up at all.
My view/edit model:
public class AdminGameEditModel
{
[Required]
public int GameID { get; set; }
[Required(ErrorMessage="A game must have a title")]
[DisplayFormat(ConvertEmptyStringToNull=false)]
public string GameTitle { get; set; }
[Required(ErrorMessage="A short URL must be supplied")]
[DisplayFormat(ConvertEmptyStringToNull=false)]
public string Slug { get; set; }
[Required(ErrorMessage="A box art image must be supplied")]
public HttpPostedFileBase BoxArt { get; set; }
[Required(ErrorMessage="A large image for the index page is required")]
public HttpPostedFileBase IndexImage { get; set; }
[Required(ErrorMessage="A game must have a review")]
[DisplayFormat(ConvertEmptyStringToNull=false)]
public string ReviewText { get; set; }
[Required(ErrorMessage="A game must have a score")]
public int ReviewScore { get; set; }
[Required(ErrorMessage="A game must have at least one Pro listed")]
[DisplayFormat(ConvertEmptyStringToNull=false)]
public string[] Pros { get; set; }
[Required(ErrorMessage="A game must have at least one Con listed")]
[DisplayFormat(ConvertEmptyStringToNull=false)]
public string[] Cons { get; set; }
[Required(ErrorMessage="A game must belong to a genre")]
public int GenreID { get; set; }
[Required(ErrorMessage="A game must be associated with at least one platform")]
public int[] PlatformIDs { get; set; }
}
The properties whose validation doesn't seem to be working properly are Pros, Cons, and GenreID. Here's how I'm trying to invoke them in my view:
<p>
<%: Html.Label("Genre") %>
<%: Html.ValidationMessageFor(model => Model.GameData.GenreID) %>
<%: Html.DropDownListFor(m => Model.GameData.GenreID, new SelectList(Model.AllGenres, "GenreID", "Name", Model.GameData.GenreID)) %>
</p>
<p>
<%: Html.LabelFor(model => Model.GameData.Pros) %><br />
<% for (var i = 0; i < 5; ++i)
{ %>
<input type="text" name="GameData.Pros" value="<%: (Model.GameData.Pros[i] != null && String.IsNullOrEmpty(Model.GameData.Pros[i])) ? "" : Model.GameData.Pros[i] %>" /><br />
<% } %>
<%: Html.ValidationMessageFor(model => Model.GameData.Pros) %>
</p>
<p>
<%: Html.LabelFor(model => Model.GameData.Cons) %><br />
<% for (var i = 0; i < 5; ++i)
{ %>
<input type="text" name="GameData.Cons" value="<%: (Model.GameData.Cons[i] != null && String.IsNullOrEmpty(Model.GameData.Cons[i])) ? "" : Model.GameData.Cons[i] %>" /><br />
<% } %>
<%: Html.ValidationMessageFor(model => Model.GameData.Cons) %>
</p>
The rest all show up fine. I'm stumped as to why those three aren't appearing. I don't see anything that jumps out to me as the cause. I'm using the default model binder and validation service.
Any ideas?
Well, for starters.. your input fields have no id's. Model validation doesn't work with names, only id's. But that's only part of the problem. The Model Binder is unlikely to be able to bind to arrays because arrays are immutable, this makes it hard to do iterative assignment to them. You're going to have to rethink this part of your application.
Second, your DropDownList has no default value. It will, in most cases just select the first item so there is no way for it to not be valid.
You may find this article interesting.
I'm using the following code to render an editor for my model using ASP.NET MVC 3, it works perfect, except for I don't want the user to see or edit the "Id" field in my object.
<% using (Html.BeginForm())
{ %>
<%: Html.ValidationSummary(true, "Your input has errors, please correct and try again") %>
<%: Html.EditorForModel(Model)%>
<input type="submit" value="Update" />
<% } %>
In my model for the ID Field I have the following
[Display(AutoGenerateField = false)]
public int Id{ get; private set; }
Which granted is what I thought would work based on the description of the "AutoGenerateField" parameter. However this isn't working. I don't want to have to build the whole editor just for this one little oddity....
Use [ScaffoldColumn(false)] to hide fields
You could use the [HiddenInput] attribute:
[HiddenInput(DisplayValue = false)]
[Display(AutoGenerateField = false)]
public int Id { get; private set; }