Asp.net MVC model property meta data to specify TextBox id - asp.net-mvc

With MVC, when you use something like #Html.TextBoxFor(...) the control renders using property attributes from the model for things like validation.
It also uses the class's property name as the name of the rendered HTML control. This conflicts a little with our naming conventions so I'd like to be able to control the ID a bit more.
I've added the 'htmlAttributes:' to the helper, which does what I want, but I was wondering:
How does this impact MVC's ability to instantiate the model again
when the information is posted?
Is there a way to specify the control ID using property attributes in the model class?
Thanks,
Jacques

How does this impact MVC's ability to instantiate the model again when the information is posted?
The ID attribute has absolutely no impact on anything that is posted. The ID attribute is never used when submitting a form. The only requirement is that this attribute is unique throughout your entire DOM. It is the name attribute that is used by the model binder. You cannot change this attribute anyway using the htmlAttributes because this attribute is inferred from the lambda expression used as first argument and you shouldn't need to change it anyway, otherwise you could break the way the default model binder rehydrates your view models.
Is there a way to specify the control ID using property attributes in the model class?
Yes, but it could be a little more work. You could use custom editor templates for the standard types and a custom metadata aware attribute that will pass this additional metadata information to the custom editor template. If you are interested in the implementation specifics I could provide an example but first I have to understand why you need that.

Related

Custom UIHint attribute

Is it possible to create a custom version of the UIHint attribute?
When my company first adopted MVC, we used a lot of Html.* helper methods. We are in the process of redesigning out MVC template to make use of the full power of MVC. One way we are doing this is with Display and Editor Templates.
However, one popular HTML extension method we had was to generate dropdowns for Enums. One of the options we had was to sort by the int value or the description or text of the EnumMember.
I would like to see about creating a EnumDropdown attribute that accepts several parameters that can customize the output of the HTML dropdown. However, I don't think it's possible to do this while still retaining the benefits of the UIHint attribute. Meaning, that I won't be able to simply call #Html.EditorFor(m => Model)
I had found that there is a System.Web.UI.IAutoFieldGenerator interface but it doesn't appear to do what I want. Any suggestions?
The newer versions of MVC have this built in now:
EnumDropDownListFor HTML Helper
The only thing UIHint does is suggest a Display or Editor template name. MVC will then add this name to the search path when looking for that template.
You can just use UIHint as is and have your generator create these for you in the correct folders and not have to customize it.

How to make a RequiredAttribute for create not for edit of model

I have a model containing a property of HttpPostedFileBase type, and I have created a custom validation attribute which implements RequiredAttribute to make some validations. It works perfectly when you create the model. However I don't want to make any validation when you edit the model (optional HttpPostedFileBase property when you edit the model). How do I make it?
Your attribute is simple metadata added to a property of a class. This attribute has no information about what you do with the class, i.e. if you're using this class to edit or to create a new entity.
So, the answer is that you cannot do that directly in the attribute. So the only solution is to "bypass" the attribute where you're using it, if you're editing the value. There are several alternatives:
use two different models, one for editing, the other for creating. And decorate the property only in the model for creating
remove the validation, or the error, using some code to do it: for example, you can remove the property error from the ModelState in a post action for the Edit action.
Obviously the easiest is 1. You can use a base class with all the fields, but those which have different treatement, and then inherit it for creation or edition. It's not strange to represent the same data with different models when you use MVC: a model for viewing, a model for showing the editor, a model for receiving the result of an edition... so, using several different models is not a problem at all. You can use AutoMapper or ValueInjecter to simplify moving data between entities and models.

How to dynamically add/remove validators in ASP.NET MVC at runtime?

We are relying heavily on client-side validation using MicrosoftMvcValidation.debug.js in the our current application implementation.
We have form elements and form validators being defined in the database and loaded from the database at runtime. We have viewmodel properties Answer1, Answer2, Answer3, etc., and up until now all fields were required, so we had the [Required] attribute on each of them, but now we need to apply this required annotation at runtime based on database settings since some of the questions are optional.
I don't want to do any reimplementation of validators themselves, I just want to either dynamically remove the [Required] attributes and/or their effects at runtime, or else dynamically add them at runtime.
Using ASP.NET MVC 2.
Add the [Required] attribute to any fields that could be required. As long as you don't bind a control client-side, you will bypass client validation without problems. On the server side post-back action, loop through the ModelState (which implements IDictionary) and clear the errors on the ModelState for the validators that you want to bypass.
foreach( var validator in ModelState){
if( validator.Key == "Validator_To_Bypass")
validator.Value.Errors.Clear();
}
Seems one can create a custom class that inherits ValidationAttribute that can determine at runtime how or whether validation is done. This is one way of accomplishing this requirement.

asp.net mvc implicit population of input fields

In our asp.net mvc I've created view with two partial views inside.
That view accepts model of some type, for example Customer.
First partial view doesn't have model because it is search form with empty field.
Second form is form with populated fields.
What I found out that on first view, if I have called input fields like properties in model and if I don't provide value for them, mvc implicitly binds values from model to the fields.
First I was thinking is some of kind of mistake, but then I've expiremented little bit with a code:
-I've added native input element with id and name called the same like model, input field is empty in browser
-If I try the same thing with Html.TextBox helper and don't provide value, mvc gets that value from my model object(by name of property/field) and in browser that field is populated.
Is this a bug or am I doing something wrong?
Thanx
That's by design.
I'd recomend reading:
http://asp.net/mvc
http://weblogs.asp.net/scottgu/archive/tags/MVC/default.aspx
and last but not least:
http://channel9.msdn.com/Events/MIX
especially mix10 has a tonn of sessions about mvc
all are good read and watch (-:
That is by design. If you send a model to a view and you're using the HTML input Helpers that come with ASP.NET MVC, they'll implicitly populate themselves from the model.
This is helpful in many situations. If you don't want this behavior, you can always NOT use the helpers or write your own simple helpers.

Displaying an asterix when using Html.LabelFor() with a Required property

I'm using ASP.NET MVC2 and Data Annotations.
I've decorated a property in my buddy class with the Required attribute.
Is there a way to get the Html.LabelFor() helper method to automatically display an asterix to signify that the field is required?
Only ways I can think of to do this are:
a) Extend LabelExtensions
Or
b) Manually add the asterix to the DisplayName attribute, e.g. "My Field *"
The latter is simplest, but introduces a dependency between the DisplayName and Required attributes.
Any other suggestions?
Instead of using the Html.LabelFor, you should create your own view helper which will create the label and insert the * is appropriate. You can find detailed info about how to create a new view helper (which is very easy) at http://mvcviewhelpers.codeplex.com/.
You need to create your own default templates. This article series by Brad Wilson explains how to do this:
http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html

Resources