MVC: How to make DropdownList field (with Chosen Plugin) Required - asp.net-mvc

I have declared a parameter in my model as
[Required]
public int? param{get; set;}
and defined this on a dropdown list. Everything works fine and the data validation works, until I add the plugin, Chosen. When I add the plugin, there is no validation proior to submission. How can i keep the data validation when the plugin is applied on the Select element?

As suggested here, I went to the chose js file and changed the this.form_field_jq.hide() to 'this.form_field_jq.css("position","absolute").css("left","-9999px")'

Related

Make a field not [Required] in certain situations?

I have a model that includes the following property:
[Required]
public string City { get; set; }
Basically, a user selects a stored value from a dropdown. The fields in my partial view are populated with the corresponding data. In certain circumstances, the stored data will not have a value for City. I am trying to use jQuery to check that if the field is empty, to basically not require the field and to allow submission. I have tried the following:
$("#City").attr("data-val", "false");
$("#City").rules("remove", "required");
$("#City").attr("disabled", "disabled");
$("#City").attr("aria-required", "false");
$("#City").removeAttr("required");
None of these work. On submit, the proper method is hit in the controller with a ModelState.IsValid of false and an error stating that "The City field is required."
How can I use jQuery to prevent this field from being validated on submit?
Before checking whether the ModelState.IsValid, you can remove the errors on that property of the Model ModelState["City"].Errors.Clear(); Therefore meaning regardless of what errors have occurred on your City property, the model state will be valid.
Note, this fix should be applied in the controller on the server - it is not related to jQuery.
Even though there were some great suggestions from posters, I ended up reevaluating our needs and found that the Required attribute was not required for that specific property.
Thanks for your suggestions everyone.

MVC: Client validation on list of object (At least one)

I want to implement client validation on a list of objects. I want to make sure that the list has at least one object, so I used custom validation as described here and made it client validable. This works well when the list is of simple datatype like an int.
That is
public List<int> var{get; set;}
With this I can include a Listboxfor in my view and when the form containing the list is submitted, client validation kicks in. However I now have a list of objects
public List<MyClass> var{get; set;}
Items are added to this list dynamically. I can therefore not have a ListBoxFor in my View. How can i display the list in my View so that that client validation picks it up?

Make asp.net mvc validation work without helpers

Could someone provide a good tutorial on how may I validate my html fields with unobtrusive,
but without using MVC helpers.
Is it possible at all?
I would like to keep the plain html and use input type="text" field instead of mvc helpers <%= Html.TextBox("Name") %> but still using the model validation..
public class Employee
{
[Required]
public string Name { get; set; }
}
Also is it possible with jquery Ajax?
Thanks
While it is possible to perform unobtrusive validation in MVC without using helpers, it will be painfully for you as developer to do it manually without usage of mvc helpers. Saying strictly, it will kill your performance and make your code unreadable.
Basically, unobtrusive validation consists of two parts: server side, via data-attributes to your model fields and MVC Helpers, which generate necessary markup, and client side library, jquery.validate.unobtrusive.js, which parses those markup to meaningful parts for jquery validate plugin.
So, in general, you can manually write necessary markup, as long as validation js library will be loaded, validation will work. For example, field, which is subject of validation, must be marked with data-val='true' attribute. If you want to make your field required, you should write additionally something like data-val-required="error message". For length validation - data-val-length-min="5" (obviously, minimum) data-val-length-max="50" (maximum length), data-val-length="Min 5 max 50 chars required".
While, when using normal mvc approach, it is just a question of model attribute:
[Required]
[StringLength(50, MinimumLength = 5)]
public string Name { get; set; }
and one line of code in markup:
#Html.TextBoxFor(o=>o.Name)
Nice, shiny, separates View and Model, and helps KISS.
And for second part of your question. If I understood your problem correctly, you want to validate dynamic forms. Probably it will be answer:
jquery.validate.unobtrusive not working with dynamic injected elements

Custom EditorTemplate not being used in MVC4 for DataType.Date

I'm upgrading an MVC3 application to MVC4 using the instructions from Microsoft. Everything went fairly smoothly - except a few of my date model properties are now rendering differently. For example, one of these properties is defined in the viewmodel like this:
[Required(ErrorMessage = "Required")]
[DataType(DataType.Date)]
[RegularExpression(#"([1-9]|0[1-9]|1[012])...",
ErrorMessage = "Format is mm/dd/yyyy")]
[FormatHint("mm/dd/yyyy")]
[InputSize("small")]
public string Date { get; set; }
Before upgrading to MVC4, this would be rendered via calling #Html.EditorFor(m => m.Date) which would use a custom EditorTemplate - the String.cshtml template (since it's a string!). I have some custom data annotations that formats the html so it utilizes a field layout, jQueryUI, and twitter Bootstrap on the client side. The validation is done via jquery validation unobtrusive. Anyhow, this is how it previously rendered:
Now that I'm using MVC4, the String.cshtml editor template is not being called for this property any longer. It renders like this (in Chrome using the HTML5 editor stuff, I assume):
The input element looks pretty much the same - all the jQuery validation bits are in there - the only difference seems to be the type attribute is now type="date", where before it was type="text".
I'd like to continue using the String.cshtml EditorTemplate for this datatype. I'm thinking there might be a data annotation that I can put on the ViewModel property to provide a TemplateHint for #Html.EditorFor(...). If not this, I'd like to know the custom EditorTemplate that I can write to hijack MVC4's formatting (I've already tried DateTime.cshtml - it's not being called either). If not either of those, then I'm open to suggestions on how to get my property rendering like it used to.
In MVC4, the used template is determinated from :
The UIHintAttribute if any
The DataTypeAttribute if any
The type of the property
In MVC3, the DataTypeAttribute was not used.
Your property has a
[DataType(DataType.Date)]
so the template Date.cshtml is used. If it does not exists, default rendering is executed.
You have two options to resolve your problem :
Add a UIHint("String") on your property, or
Rename your editor template from String.cshtml to Date.cshtml

String[] vs Integer[] in Struts2 action attribute

I am new t struts2. i built one page, that shows list of employees. I can seach the employes based on his name by applying filter criteria and click on find button. At the same time, i provided check box in the left side for each employee name for delete operation. for all checkboxes, i gave Integer[] attribute name which is declared in Custom Actionclass.deleteaction is working fine. But when i click Find button the action is not getting submitted. Then i changed Integer[] to String[] both functions are working fine. What will be the problem? is it something like, attributes should only be String type.
The cause of your problem is that the Struts2 checkbox sets a boolean property on the action class:
Struts 2 Form Tags: Checkbox
When you defined the checkboxes as an Integers, the framework couldn't covert the boolean to an Integer. However it was able to convert the boolean to Strings. If you check the results in your action class, you should see the String[] populated with "true" and "false".
In general Struts2 is pretty good at converting submitted form data to whatever object type you want. Check out the docs on type conversion for more info.

Resources