Is there any way to access any attributes (be it data annotation attributes, validation attributes or custom attributes) on ViewModel properties from the view? One of the things I would like to add a little required indicator next to fields whose property has a [Required] attribute.
For example if my ViewModel looked like this:
public class MyViewModel
{
[Required]
public int MyRequiredField { get; set; }
}
I would want to do something in the EditorFor template like so:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<int?>" %>
<div class="label-container">
<%: Html.Label("") %>
<% if (PROPERTY_HAS_REQUIRED_ATTRIBUTE) { %>
<span class="required">*</span>
<% } %>
</div>
<div class="field-container">
<%: Html.TextBox("") %>
<%: Html.ValidationMessage("") %>
</div>
The information you're looking for is in ViewData.ModelMetadata. Brad Wilson's blog post series on Templates should explain it all, especially the post on ModelMetadata.
As far as the other ValidationAttributes go, you can access them via the ModelMetadata.GetValidators() method.
ModelMetadata.IsRequired will tell you if a complex type (or value type wrapped in Nullable<T>) is required by a RequiredAttribute, but it will give you false positives for value types that are not nullable (because they are implicitly required). You can work around this with the following:
bool isReallyRequired = metadata.IsRequired
&& (!metadata.ModelType.IsValueType || metadata.IsNullableValueType);
Note: You need to use !metadata.ModelType.IsValueType instead of model.IsComplexType, because ModelMetadata.IsComplexType returns false for MVC does not consider to be a complex type, which includes strings.
I would suggest not doing that way because you're adding logic in the view which is a bad practice.
Why don't you create a HtmlHelper or LabelExtension, you can call ModelMetaProvider inside the method and find out whether the property has Required attribute decorated?
Related
Short of overriding ViewData.TemplateInfo.HtmlFieldPrefix with an empty string, is there a way to keep the prefix from coming through on a nested set of strongly-typed EditorFor or DisplayFor helper calls?
Here's the ugly markup/code I have working so far:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Web.Mvc.SelectList>" %>
<% ViewData.TemplateInfo.HtmlFieldPrefix = ""; %>
<%=Html.DropDownList("sort", Model)%>
I've tried the *For overload that allows specifying htmlFieldName but that only changes the immediate level. If I have a prefix at the point of that call, I just change what is appended to the prefix.
I could write the template markup by hand, but doing so for a SelectList object seems like I will just end up copying over the MVC source with a single tweak since it involves object data binding logic.
If you have a property on your view model, rather than just doing dropdown list directly on the model, you can put a DataAnnontation attribute on it.
public class MyModel
{
[Display(Name="Your Favorite Choices")]
public string[] Choices {get; set;}
}
then in your code
<%= Html.LableFor(m => m.Choices) %><br />
<%=Html.DropDownList("sort", Model.Choices)%>
Should use that name.
[Hope I got it right from memory. :)]
Here's the MSDN link:
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.displayattribute.aspx
Not sure if I understand your question, but, if you render the "child" views as partials instead of EditorFor then the fields will not be prefixed.
The standard MVC example to draw an item with the appropriate View Template is:
Html.DisplayFor(m => m.Date)
If the Model object has a property named Date of type DateTime, this returns a string with the HTML from the Display/DateTime.ascx template.
Suppose you wanted to do the same thing, but couldn't use the strongly-typed version - you didn't know the Model's type for this View at compile time. You use the older:
Html.Display("Date");
So here's the hard part.
Suppose the Model is IEnumerable. You don't know what those objects are at compile-time, but at run-time they happen to be objects with a Date of type DateTime again, like:
public class ModelClass
{
public DateTime Date { get; set; }
}
Now suppose you want your View to iterate over those objects and render each out. If all you cared about was the value you could do this:
<%
StringBuilder sb = new StringBuilder();
foreach(object obj in (IEnumerable<object>)Model)
{
Type type = obj.GetType();
foreach(PropertyInfo prop in type.GetProperties())
{
// TODO: Draw the appropriate Display PartialView/Template instead
sb.AppendLine(prop.GetValue(obj, null).ToString());
}
}
%>
<%= sb.ToString() %>
I'm obviously taking some shortcuts to keep this example focused.
Here's the point - how do I fulfill that TODO I've written for myself? I don't just want to get the value - I want to get it nicely formatted like Html.Display("Date"). But if I just call Html.Display("Date"), it inspects the Model, which is an IEnumerable, for a property named Date, which it of course does not have. Html.Display doesn't take an object as an argument to use as the Model (like Html.Display(obj, "Date"), and all the classes and methods I can find that lie underneath appear to be internal so I can't tweak and call into them directly.
There must be some simple way to accomplish what I'm trying to do, but I can't seem to find it.
Just to make sure I'm being clear - here's an example of the code of DateTime.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime>" %>
<%= Model.ToString("MM/dd/yyyy") %>
And so, ideally, the output from this View that can take any Model, but in this case a list of 3 of these ModelClass objects above, would be:
11/10/2001
11/10/2002
11/10/2003
Because the code would find the Display PartialView for DateTime and render it appropriately for each.
So - how do I fulfill the TODO?
Have a look at the template code in this excellent post from Phil Haack. It seems to come close to what you are looking for: http://haacked.com/archive/2010/05/05/asp-net-mvc-tabular-display-template.aspx
I've found one potential solution to this but I'm not in love with it; it requires using several file-based templates, meaning you can't abstract this easily into a code library for use in multiple projects.
The View:
<%
StringBuilder sb = new StringBuilder();
Type itemType = Model.GetType().GetGenericArguments()[0];
sb.AppendLine("<table>");
// Pass in the Model (IEnumerable<object>)'s generic item type as
// the Model for a PartialView that draws the header
sb.Append(Html.Partial("DisplayTableHead", itemType));
foreach(object item in (IEnumerable<object>)Model)
{
sb.Append(Html.Partial("DisplayTableRow", item));
}
sb.AppendLine("</table>");
%>
<%= sb.ToString() %>
Views/Shared/DisplayTableHead.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Type>" %>
<tr>
<%
foreach (PropertyInfo prop in Model.GetProperties())
{
%>
<th><%= prop.Name %></th>
<%
}
%>
</tr>
Views/Shared/DisplayTableRow.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<tr>
<%
Type modelType = Model.GetType();
foreach (PropertyInfo modelField in modelType.GetProperties())
{
%>
<td><%= Html.Display(modelField.Name) %></td>
<%
}
%>
</tr>
But I now see the major flaw in this solution, which is that Clicktricity's posted solution acknowledges details in the ModelMetadata - like whether that particular property is set for display, whether it's complex or not, etc.
Is there a good reason to use the strongly typed html helper...
<%: Html.DisplayTextFor(model => model.Email) %>
As opposed to...
<%: Model.Email %>
Consider the following Model:
public class MyModel
{
public string Name { get; set; }
[DisplayFormat(NullDisplayText = "No value available!")]
public string Email { get; set; }
}
in my view:
<%= Html.DisplayTextFor(m => m.Email) %>
<%: Model.Email %>
The first line will display "No value available" if we leave the Email to be 'null' whereas the second line will not display anything.
Conclusion:
Html.DisplayTextFor will take into consideration the DataAnnotations on your properties, <%: Model.Email %> will not.
Also <%: Model.Email %> will throw an "Object reference error" when the value is null, but <%= Html.DisplayTextFor %> wont.
DisplayTextFor will also get called during "DisplayFor" and "EditFor" execution. This will ensure that any templated helpers will display the text using the correct Templated Helpers if set ... so a change to the single templated helper will propogate through all displays of that text item ... simple display, edit form, create forms etc etc.
Well, DisplayTextFor will not break if you do not pass in a model (or pass null). Model.Email will throw an exception on null. So, DisplayTextFor is more robust.
The point of the strongly typed helpers is to allow greater compile time checking. This is very handy when refactoring.
DisplayTextFor allows using a consistent construct (with the other strongly typed helpers) throughout the page. Some people might find that more appealing.
DisplayTextFor also allows you to pass the names of templates and fields as parameters.
Given the following MVC mark-up:
<p>
<label for="forenamesLabel">Forename(s):</label>
<%: Html.TextBoxFor(model => model.ConsultantRegistrationDTO.Forenames) %>
<%: Html.ValidationMessageFor(model => model.ConsultantRegistrationDTO.Forenames, "*") %>
</p>
How is it possible for me to accurately set the label/#for attribute to the id of the generated TextBox by MVC? If I use #id as an HTML option, wouldn't that break my binding?
You can use
Html.LabelFor(c model => model.ConsultantRegistrationDTO.Forenames)
Then in your model you need to specify the DisplayNameAttribute from System.ComponentModel.DataAnnotations. So your model would look something like this:
public class ConsultantModel
{
[DisplayName("Forenames")]
public string Forenames { get; set; }
}
As was suggested by Keltex you can use Html.LabelFor with a DisplayName decorator. A few considerations that go along with this.
LabelFor and DisplayName decorators are specific to MVC 2. This may or may not be an option for you.
Using this method, specifically using the DisplayName decorator, introduces View concerns into your Model which is sometimes not desirable. It is usually better to create a ViewModel and use the decorator there to preserve separation of concerns.
This also allows you to use the DisplayNameAttribute when your model is auto-generated as you've said yours is.
This same question was asked here and an answer was given which is workable, but with the finalization of the ASP.Net MVC framework, I wondered if there was a better solution.
If I have the following class structure how do create the view page and more importantly return the data back to the controller.
public class Person {
public int Id {get;set;}
public string Name {get;set;}
public IList<TelNos> TelNos {get;set;}
}
public class TelNos{
public string Type {get;set;}
public string Number {get;set;}
}
My understanding is that within the page I would could include the following (assuming strongly typed view):
<% foreach (var telNo in Model.Product.TelNos)
{%>
<p><label for="telNo.Type">Type of Number</label>
<%= Html.TextBox("telNo.Type")%>
<%= Html.ValidationMessage("telNo.Type", "*")%>
</p>
<p><label for="telNo.Number">Type of Number</label>
<%= Html.TextBox("telNo.Number")%>
<%= Html.ValidationMessage("telNo.Number", "*")%>
</p>
<%} %>
Assuming that I initiated 2 TelNos objects I would then see 2 sets of text boxes within the view.
When that form is posted back, the suggestion on the previous post was to iterate through the FormCollection within the post method:
[AcceptVerbs( HttpVerb.POST )]
public ActionResult Whatever( FormCollection form )
{
....
}
However is that now the best approach, or have the further updates to MVC provided a better solution?
Thanks, Richard
There have not been any updates or best practices (as far as I'm aware of) to handling dynamic forms on post. The still tried and true ways are to either databind your information, or iterate through it in the FormCollection. If you take a look here it might help you with the databinding. OR in the latter case, you could iterate through the forms collection calling up the various values with their string name. Although this could possibly have some conflicts since they are all going to have the same id of
"telNo.Type"
"telNo.Number"
You might have to do some manipulation to have it be something like
"telNo.Type[i]"
"telNo.Number[i]"
where i is a number in sequence for that object in the list. You could also have it be something other string combination that generates a unique id for that object so that you can get the type and the number.
"object[i].telNo.Type"
"object[i].telNo.Number"
It really depends on how you think you can best implement it. Sometimes getting databinding to work for dynamic forms can be a pain and it's easier to just iterate through the collection, then using something like LINQ to get the ones you want/group them/etc.
Thanks for your answer. Your answer did give me an idea, which I think is different to what you are suggesting.
If I include in the view an index to the object, then the Default Model builder takes the values and assigns them to the associated objects. The view code is as follows:
<% int i=0;
foreach (var telNo in Model.Product.TelNos)
{%>
<p><label for="telNo.Type">Type of Number</label>
<%= Html.TextBox("telNo"+i.ToString()+".Type")%>
<%= Html.ValidationMessage("telNo"+i.ToString()+".Type", "*")%>
</p>
<p><label for="telNo.Number">Type of Number</label>
<%= Html.TextBox("telNo"+i.ToString()+".Number")%>
<%= Html.ValidationMessage("telNo"+i.ToString()+".Number", "*")%>
</p>
<%i++;
} %>
Richard
I like the idea at ASP.NET MVC Partial View with Form which in turn links to Model Binding To A List
I think it's better for two reason:
Going through FormCollection violates the idea of separating view form controller. Controller will have too much knowledge on how the data is displayed.
Writing a unit test will be painful. you'll need to stick all the values into the form controller manually