ASP.NET MVC Validate dynamic form elements - asp.net-mvc-3

I want to add the ability to build a form in my app. The user adds input fields to the form in the UI of my app, and for each form element she can specify data-type.
I use ASP.NET MVC 3, and want to use as much as I can of the validation mechanism supported by the frameworks. For my own forms in the app, I decorate each ViewModel with dataannotations to and use client validation.
Is there any way I can add those annotations to a dynamic ViewModel?
It's fine to use e.g. #Html.TextBox("name"), but how do I mimic the data annotations, so that jQuery Validate and the unobtrusive plugin picks them up correctly?

Have you tried adding the data-dash-attributes like this? (Hint: Use an underscore instead of the dash, it will be translated to a dash in the according attribute)
#HtmlTextBox("name", new { data_... = "some value", data_... = "some value" })

Related

Adding validation property attributes in views with Html.EditorFor() methods not inside a Html.BegingForm() method

I have noticed that validation attributes are only added to the elements that were created via Html.EditorFor() helper method and which are inside a Html.BegingForm() method, that respectively creates the "Form" tag and attributes.
Is there any way, besides manually creating the elements and attributes of course to add the required validation attributes to elements created with helper methods and which are not inside the Html.BegingForm() method ?
I need to validate at the client side and don't want to manually either create said attributes or script this behavior explicitly and instead take advantage of the MVC feature that adds said attributes automatically as per metadata on the model for use with the jquery-validate plugin at the client-side.
The unobtrusive validation attributes emitted only if:
the UnobtrusiveJavaScriptEnabled flag is set to true
the ViewContext.FormContext is not null (e.g the Html helper is executed inside a Html.BeginForm block)
So you can manually create a FormContext and assign it to ViewContext.FormContext before using your Html helpers:
#{
ViewContext.FormContext = new FormContext();
}
#Html.TextBoxFor(x => x.SomeProperty)
However you should note that with this approach you lose the from nesting feature of Html.BeginForm so if you want to create a new logical form you need to again create new FormContext() and manage the old context yourself.

Amounts with "$" fail jQuery unobtrusive validation

I'm using jQuery unobtrusive validation version 2.0 for MVC3. I also have the latest jquery.validate (v 1.9). I have a popup form with this code:
$(document).ready(function () {
$('#createForm').submit(function () {
$.validator.unobtrusive.parse($('#createForm'));
(more)
(The third line is necessary so that the form fields added by javascript will be validated.)
The validation works fine except that a value such as $1,000.00 entered into an input tag that is bound to a decimal property in the viewmodel is invalid, while 1,000.00 is valid. Clearly the "$" is casting the value as a string in the eyes of the validator.
I have researched this for many hours and I have only found one other similar question posted (also on SO and it was unanswered). I can't believe that this has been encountered by every MVC3 developer who handles currency values in a modal dialog, otherwise we would surely have some resolution by now, right?
I have resolved the issue on the server side by creating a DecimalBinder. Now I need a solution for the client-side validation. I have been looking hard at the API for jquery.validate.unobtrusive but I can't seem to find a hook. I do not want to modify any standard javascript library.
How about a custom validation method which first looks to strip off any $ characters prior to validating?
var currentVal = (control's actual value);
currentVal = currentVal.replace('$','');
Then continue with validation. The obvious downside is the need for custom validators.

MVC3 Force Validation of Hidden Fields

I need to enable the validation of hidden fields using ASP.net MVC3 unobtrusive validation.
The reason behind this is a jquery plugin which hides the original input field to show something fancier. But this disables validation of the field as it becomes hidden.
I tried to use the following code but without success.
$("form").validate({
ignore: ""
});
Thanks
With a hint from this Question I was able to manipulate the options of the unobtrusive validator object.
var validator = $("#myFormId").data('validator');
validator.settings.ignore = "";

MVC3 Finding a control by its Name

I have a C#.Net web app and I am trying to access one of the HTML/ASP Text Boxes in the Controller for the Edit View of my Proposal model. In a non-MVC app, I was able to do this using Control.ControlCollection.Find(). Is there an equivalent for a MVC3 project?
You ask for an equivalent of Control.ControlCollection.Find() in MVC?
In MVC your controller is not aware of controls.
The controller just receives data via parameters and returns data via the function result.
What do you want to do with the control in your controller code?
If you want to access the value, you should bind it to a parameter:
View:
<input name="MyControl" type="text" />
Controller:
public ActionResult MyAction(string MyControl) {
// MyControl contains the value of the input with name MyControl
}
The MVC pattern was designed to keep things separated.
The View has no knowledge of the controller at all
The Controller only knows that a view exists and what kind of data that it needs. It do not know how the data is render.
Hence, you can never get information about controls/tags in the view from the controller. You need to use javascript/jQuery in the view and invoke the proper action in the controller.
In an MVC-application you don't have controls like in a webform-application.
In MVC you collect your required data in the controller and pass it to the view.
Typicaly the view is a HTML-page with embedded code.
In opposite to controls in webforms which produce HTML and handles the post-backs in MVC you have to do all this manually. So you don't have controls with properties and events wich you can access easily in the controller and you have to handle all your posts with your own code.
Thats sounds as it is a lot of more work - and indeed it could be if you implement the behaviour of complex controls - but MVC applications are much better to maintain and you have 100% influence to the produced HTML.
Well probably i am late for this but it should help others in future...u can store ur value in hidden field in view and then access that value in controller by following code..
Request.Form["hfAnswerOrder"].ToString();
Point - hfAnswerOrder is the ID of the hidden field
My Control in cshtml page..
#Html.Hidden("hfAnswerOrder", Model.Answers.ToList()[0].AnswerOrder)

create custom controls mvc3

Just starting to get the hang of MVC3 and want to start building out some custom controls that I can just drop into a view. Specifically I want to be able to drop in some html form controls that will automatically add some javascript for validation.
something like this is what I'd want:
#Html.VTextBox("MyTextBox","",new {#vType="PhoneNumber", #vMessage="You Must Enter a Phone Number" })
when the page is rendered, I'd want it to search for any custom elements I create then drop in the appropriate javascript to validate client side. I did something very similar to this with asp.net web forms for custom controls ie
<ucc:VTextBox ID="MyTextBox" runat="server" message="You must fill this in" />
just wondering if MVC3 offers the same extensibility. Any resources or advice you can provide would be greatly appreciated.
TIA
To start off with, you'll need to look into extension methods and more specifically, how to create extension methods for the HtmlHelper class so you could write code like the example you've shown above.
For the example you've shown above, you could write code like this:
public MvcHtmlString VTextBox(string name, object value, object htmlAttributes)
{
StringBuilder html = new StringBuilder();
// Build your html however you want
// Here's a simple example that doesn't
// take into account your validation needs
html.AppendFormat("input type=\"text\" name=\"{0}\" value=\"{1}\" />", name, value);
return MvcHtmlString(html.ToString());
}
Then in your view you can use the example above like so:
#Html.VTextBox("MyTextBox","",new {#vType="PhoneNumber", #vMessage="You Must Enter a Phone Number" })
NOTE: You'll need to import the namespace the extension method is in to your view. Simplest method, put a #using ExtensionMethodNamespace at the top of your view. You can make the namespace automatically imported to all your views by fiddling with the web.config (and maybe the Global.asax).
ADDENDUM: Please note RPM1984's comment below where he advises to use TagBuilder in place of StringBuilder which is sound advice since this is the exact scenario TagBuilder was designed for. He also mentions strong typing the helper to the model which is also great advice.

Resources