How to disable client side validation field wise - asp.net-mvc-3

suppose my form has 5 fields and first two will be validated at client side and next one will not but next will. i got the guidance like
<div class="editor-field">
#{ Html.EnableClientValidation(false); }
#Html.TextBoxFor(m => m.BatchId, new { #class = "k-textbox" })
#{ Html.EnableClientValidation(true); }
</div>
but it did not work. i wrote Html.EnableClientValidation(true)
and after second field and before 3rd field i wrote Html.EnableClientValidation(false)
and again i wrote Html.EnableClientValidation(true) before 4th field. but i saw all fields are getting validated at client side.
thanks

Try #Html.TexBoxFor(model => model.BatchId, new {#class = "k-textbox", data_val = false})
That should disable validation for field

Related

Required validation on hidden field

I am using client side validation on hidden field in asp.net MVC. I am using required validation using data annotations. I am trying to validate hidden field but it’s not working.
My Model
[Required(ErrorMessage = "From date is required")]
public DateTime? FromDate { get; set; }
My View
#Html.HiddenFor(m => m.FromDate, new { ID = "hfdFromDate" }
#Html.ValidationMessageFor(m => m.FromDate)
I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.
Thanks in advance.
As some have pointed the validation isn't performed because the "hidden" property is set.
I had the same issue and ended up using the style tag:
#Html.TextBoxFor(m => m.Foo, new { style = "visibility:hidden"})
The validation is then performed.
Added this line before form.valid().
form.data("validator").settings.ignore = "";
where form is your form element.
In my case :
var form = $("#myForm");

Validation of DropDownListFor is not working in MVC3?

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" })

ASP.NET MVC 3 #Html.DropDownListFor ignoring selectedValue

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.

ASP.Net MVC3 Html.PasswordFor does not populate

In my view I have the following element
#Html.PasswordFor(model => model.Password)
This is on a screen that creates/updates user details. When I am trying to update the user this field remains blank. When I change this element to a TextBoxFor it gets the data. How do I get to populate the Password field.
As described above, it is better to avoid doing this for security reason. if you still want to persist the password so that you proceed from where the current validation failed, you can use the HTML helper with html attribute parameter:
Html.PasswordFor(x => x.Password, new { value = Model.Password})
This is as designed. Passwords are not filled to prevent accidental resubmits, and to prevent the page from containing unencrypted passwords. Obviously the password was wrong to begin with if you're posting back the credentials.
In your case, you could create an extension that does input the data, or just use an HTML input of type password.
MVC protects you from doing something like this for a reason. You shouldn't actually be able to do this because the users password should not be stored unencrypted and unhashed. If your goal is to end end up on http://plaintextoffenders.com/ though, you can do something like:
<input type="password" name="Password" id="Password" value="#Model.Password" />
I found this workaound. I needed my password shown in the form:
#model User
#{
#Html.Label(Model.Username, new { #class = "label" })
#Html.TextBoxFor(Model => Model.Username, new { #class = "form-control" })
#Html.Label(Model.Password, new { #class = "label" })
#Html.TextBoxFor(Model => Model.Password, new { #class = "form-control make-pass" })
}
<script type="text/javascript">
$(".make-pass").attr("type", "password");
</script>
This will make your input password-type without losing the value.
As mentioned before, its by design. But that can be wrong. We just got a new user who was confused by the empty password after the page refresh when he just added a password. So a simple fix is to change the label 'Password' to 'New password'. Now its clear why this input box is always empty.
If you're using asp-for attribute you can also do:
<input type="password" placeholder="#(Model.Password != null ? String.Concat(Model.Password.ToCharArray().Select(p=>"*")) : "Password")" asp-for="Password">

ASP.NET MVC 3 - Validation Question

Good evening everyone I have a question regarding validation of drop-down list values. I have a view that is bound to a view model type called ReservationData.
This object contains a property CustomerVehicles of type List<VehicleData>. VehicleData has two int properties VehicleMakeId and VehicleModelId.
On my view I am trying to loop over the number of items in the CustomerVehicles collection and displaying two dropdowns for each, a vehicle make dropdown and a vehicle model dropdown using DropDownListFor.
When I try to submit and validate I do not see any validation errors displayed on the screen.
Just in case you are wondering I have added a ValidationMessageFor for each dropdown as well. I am not sure if this is an issue with the structure of my view model and its complexity and how the controls need to be named or how the ids need to be set. Any help would be greatly appreciated.
Here is the code for the looping over the collection:
#for (var i = 0; i < Model.CustomerVehicles.Count(); i++)
{
var vehicleNumber = i + 1;
<div class="vehicle-selection-wrapper">
<div class="content-container">
<h3>
Vehicle #vehicleNumber</h3>
<img class="vehicle-image" alt="manufacturer image" src="#Url.Content("~/Content/images/default-vehicle.gif")" /><br />
#Html.LabelFor(m => m.CustomerVehicles[i].VehicleMakeId)
#Html.DropDownListFor(m => m.CustomerVehicles[i].VehicleMakeId
, new SelectList(Model.VehicleMakes, "Id", "Name")
, #UIDisplay.Dropdown_DefaultOption, new { #class = "long-field" })<br />
#Html.ValidationMessageFor(m => m.CustomerVehicles[i].VehicleMakeId)<br />
#Html.LabelFor(m => m.CustomerVehicles[i].VehicleModelId)
#Html.DropDownListFor(m => m.CustomerVehicles[i].VehicleModelId
, new SelectList(new List<CWR.Domain.VehicleModel>(), "Id", "Name")
, #UIDisplay.Dropdown_DefaultOption, new { #class = "long-field" })
#Html.ValidationMessageFor(m => m.CustomerVehicles[i].VehicleModelId)
</div>
</div>
}
Ok so I also noticed that in the generated HTML the selects that are generated are missing the HTML5 data-val attributes that are associated to elements to handle validation. Here is the generated HTML
<select class="long-field" id="CustomerVehicles_0__VehicleMakeId" name="CustomerVehicles[0].VehicleMakeId"><option value="">-- Select --</option>
</select><br />
<span class="field-validation-valid" data-valmsg- for="CustomerVehicles[0].VehicleMakeId" data-valmsg-replace="true"></span><br />
<label for="CustomerVehicles_0__VehicleModelId">Model</label>
<select class="long-field" id="CustomerVehicles_0__VehicleModelId" name="CustomerVehicles[0].VehicleModelId"><option value="">-- Select --</option>
</select>
<span class="field-validation-valid" data-valmsg-for="CustomerVehicles[0].VehicleModelId" data-valmsg-replace="true"></span>
Additionally in my VehicleData class the VehicleMakeId and VehicleModelId properties are decorated with a Required attribute.
UPDATE:
Ok so I was testing and noticed that if I keep my code identical except I swap the Html.DropdownListFor calls with Html.TextboxFor calls then the validation works. What could be causing this? Could it be a framework bug with the unobtrusive validation?
UPDATE: Contains Fix
So after posting this same question on the ASP.NET Forums, I was able to get a solution. In the post you will be able to see that there is a bug in the unobtrusive validation framework and how it handles validation of dropdownlists. The user counsellorben does a good job in explaining the problem as well as a solution (including sample code) that will assist others in avoiding this issue in the future, or at least until Microsoft builds in a fix in to the framework.
Thank you everyone for your assistance.
I too have come across this obviously massive oversight regarding client side validation with dropdownlists in MVC 3 and the best solution I can offer is to put the missing HMTL attributes in yourself.
In your view model create a property like this.
public Dictionary<string, object> CustomerVechicleAttributes
{
get
{
Dictionary<string, object> d = new Dictionary<string, object>();
d.Add("data-val", "true");
d.Add("data-val-required", "Please select a Vechicle.");
return d;
}
}
Then in your code, enter
#Html.DropDownListFor(m => m.CustomerVehicles[i].VehicleMakeId
, new SelectList(Model.VehicleMakes, "Id", "Name")
, #UIDisplay.Dropdown_DefaultOption,
**Model.CustomerVechicleAttributes** })
Just add the Model.CustomerVechicleAttributes as htmlAttributes to your dropdownlist.
This will inject the necessary attributes that are missing. You will of course need to add any other attributes you may need like your class attribute.
Hope this helps.
This is the simpliest way I found to do it, just adding data-val-*-* attributes in HtmlAttributes of DropDownListFor, inside the view. The following method works with RemoteValidation too, if you do not need remote validation, simply remove the elements containing data-val-remote-*:
#Html.DropDownListFor(m => m.yourlistID, (IEnumerable<SelectListItem>)ViewBag.YourListID, String.Empty,
new Dictionary<string, object>() { { "data-val", "true" },
{ "data-val-remote-url", "/Validation/yourremoteval" },
{ "data-val-remote-type", "POST" }, { "data-val-remote-additionalfield", "youradditionalfieldtovalidate" } })
I hope it may help. Best Regards!
you should try to add data annotations on your view model properties first so you could see the validation messages.
you might find what you need here
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx
or create custom ones if needed.
what exactly do you need to validate?
I had exactly the same problem with the field getting correctly validated in TextBoxFor but not in DropDownListFor.
#Html.DropDownListFor(m => m.PaymentTO.CreditCardType, Model.CreditCardTypeList, "Select Card Type", new { style = "width:150px;" })
Since I had another DropDownListFor working on the same page, I knew that it wasn’t a generic DropDownListFor problem. I also have a complex model and parent object PaymentTO wasn’t initialized. When I set viewTO.PaymentTO = new PaymentTO(); in the Controller, the validation for the DropDownListFor started to work. So there is probably a problem with DropDownListFor, but the fix can be as simple as initializing the object in the controller.

Resources