Validation is Working on Other Input type text element but not working on DropDownListFor
Class Purchase Input Property Code
[Required]
public string LedgerId { get; set; }
Class View Model Code
PurchaseViewModel purchaseVM = new PurchaseViewModel
{
// PurchaseInput=purchaseInput,
Ledger = uw.LedgerRepository.Get().Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.LedgerName }),
};
View
<div class="column">
<div class="labelField">
#Html.LabelFor(model => model.PurchaseInput.LedgerId, "Party")
</div>
<div class="ItemField">
#Html.DropDownListFor(model => model.PurchaseInput.LedgerId, new SelectList(Model.Ledger, "Value", "Text"))
#Html.ValidationMessageFor(model => model.PurchaseInput.LedgerId)
</div>
</div>
On the face of it, it seems that you do not have an empty item in your select list. The validation will only trigger if the user selects a dropdown item with string length of zero. If you examine the Html source can you see the validation attributes on the dropdown ( depending on whether you are using unobtrusive validation or not)?
Yes, there are problems with validation of DropDownListFor. look at this link. They get validation data manually from metadata - http://forums.asp.net/t/1649193.aspx
Although this is a workaround, at least it fires some sort of validation. Try:
#Html.DropDownListFor(model => model.PurchaseInput.LedgerId, new SelectList(Model.Ledger, "Value", "Text"), new { #class = "required" })
Related
I have a textbox and want to display the field is required when the form gets submitted. The error message do appear in case i click on the textbox and tab to go to next textbox. I have the 'Required' data annotation on my model like this:
[DisplayName("Shipment Number")]
[Required]
public string ShipmentNumber { get; set; }
My View looks like this:
<div class="col-sm-8">
#Html.TextBoxFor(model => model.ShipmentNumber, new {#class = "form-control", #maxlength = "8", #title = "Maximum length is 8"})
#Html.ValidationMessageFor(model => model.ShipmentNumber)
</div>
Oh, i also added these in $function:
$("form").kendoValidator();
$.validator.setDefaults({
ignore: ""
});
When i leave the textbox blank and submit the form, the form gets submitted without showing the error message i.e. 'The Shipment Number is required!'.
P.S: I also tried DataAnnotation:
[Required(ErrorMessage = "ShipmentNumber Is Required")]
Does anyone know how i can achieve this?
Update:
This fixed it:
Changes in Razor code to make textbox required and added required error message.
#Html.TextBoxFor(model => model.ShipmentNumber, new {#class = "form-control", #maxlength = "8", #title = "Maximum length is 8", data_required_msg = "Shipment Number is required!", required = "required" })
In button submit code in javascript, did this:
var validator = $(".form-horizontal").kendoValidator().data("kendoValidator");
if (validator.validate()) {
//code that needs to be executed if it is valid
}
Note: I also got rid of data annotation from modal class, #Html.ValidationMessageFor and $("form").kendoValidator code.
Try forcing the validation when you click your button:
// Validate the input when the Save button is clicked
$("#save").on("click", function() {
if (validator.validate()) {
// If the form is valid, the Validator will return true
save();
}
});
or
$("form").submit(function(event) {
event.preventDefault();
if (validator.validate()) {
status.text("Hooray! Your tickets has been booked!")
.removeClass("invalid")
.addClass("valid");
} else {
status.text("Oops! There is invalid data in the form.")
.removeClass("valid")
.addClass("invalid");
}
});
See http://docs.telerik.com/kendo-ui/framework/validator/overview
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 have an IList in my model. Which i am displaying as radio buttons.
But when i submit the form the value is not correct and the model state is not valid and where the value for the selected radio button should be there is 'Count =0'
This the option in model:
[Display(Name = "My enquiry is regarding: *")]
public IList<Industry> A1_EnquiryRegarding { get; set; }
controller:
populate list:
Industry blank = new Industry();
blank.Id = 0;
blank.Name = "Other";
IList<Industry> industryList = manager.GetIndustries();
industryList.Insert(industryList.Count, blank);
EnquiryModel.A1_EnquiryRegarding = industryList;
html:
<td>
<div class="editor-label">
<b> #Html.LabelFor(m => m.A1_EnquiryRegarding)</b>
</div>
<div class="editor-field">
#foreach (var radiobutton in Model.A1_EnquiryRegarding) {
#Html.RadioButtonFor(m => m.A1_EnquiryRegarding, radiobutton.Name)
<label>#radiobutton.Name</label>
<br></br>
}
#Html.ValidationMessageFor(m => m.A1_EnquiryRegarding)
</div>
</td>
where am i goign wrong? why am i not getting the correct selected value back?
Edit:
[HttpPost]
public ActionResult EnquiryForm(Enquiry Enquiry)
{
When you post back, your collection of complex object is not recreated. Instead, there is only one string value passed with the selected value of the radio. Your model for the update action should only include one name.
Implement your radiolist as follows:
#foreach (var radiobutton in Model.A1_EnquiryRegarding) {
#Html.RadioButton("selectedIndustry", radioButton.Name);
}
All your radio buttons should have the same name, but different values. That way, when you call your Post action, you just search for parameter "selectedIndustry".
[HttpPost]
public ActionResult MyPostAction(string selectedIndustry) {
}
I have an MVC3 drop down list that come from this code on the controller.
private SelectList progCodesList = new SelectList(new[] { "Description", "Requirements", "Development", "Testing", "Documentation" });
How can I fill the fields from a repository, to build the drop down dynamically?
Thanks.
Assuming you have the progCodes in a database table, with progCode having the text, and progCodeId with a unique id, then you can read the table into a list of SelectListItem as follows:
private DbContext _db = new DbContext();
var progCodesList = _db.progCodes.Select(x => new SelectListIem()
{
Text = x.progCode,
value = x.progCodeId
}).ToList();
You can then pass this List<SelectListItem> to your view either in a strongly-typed model, or using the ViewBag.
You need to pass the progCodesList to the ViewBag in your controller method using something like:
ViewBag.ProgCodeId = progCodesList;
Then in your view, you need to fill the drop down like this:
<div class="editor-label">
#Html.LabelFor(model => model.ProgCodeId, "ProgCode")
</div>
<div class="editor-field">
#Html.DropDownList("ProgCodeId", String.Empty)
#Html.ValidationMessageFor(model => model.ProgCodeId)
</div>
In my asp.net MVC 3 project I would like to create a contact that's related to a company.
You can either directly create a contact OR go via the company details view and add a new contact passing the companyId to set that company already in the dropdown on the contact create form.
The problem is that I can 't get the passed company as default in my dropdown.
Global.asax
routes.MapRoute("contactCreate", "contact/toevoegen/{companyid}", new { action = "ContactCreate", controller = "Backend", companyid = UrlParameter.Optional });
Controller method
public ActionResult ContactCreate(int? companyid)
{
Contact contact = new Contact();
ViewBag.StatusList = srep.getContactStatusses();
ViewBag.CompanyId = companyid;
return View(contact);
}
View
#model xxx.Models.Contact
...
<div class="editor-label">
#Html.LabelFor(model => model.bedrijf_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.bedrijf_id, new SelectList(ViewBag.Bedrijven, "bedrijf_id", "bedrijf_naam",ViewBag.CompanyId), "--Kies bedrijf--")
#ViewBag.CompanyId
#Html.ValidationMessageFor(model => model.bedrijf_id)
</div>
...
#ViewBag.CompanyId has a value.
Any idea why it's not setting the selected value?
When doing a "DropDownListFor" it will try to match up the value passed in from the model for the selected value. So in your example it will use "bedrijf_id" as the selected value. It looks like you want the selected value to be from something outside of your model.
From the comments I think what you want is just a DropDownList as follows:
#Html.DropDownList("DropDownList", new SelectList((ViewBag.Bedrijven, "bedrijf_id", "bedrijf_naam", ViewBag.CompanyId), "--Kies bedrijf--")
Hope this helps.