TextBoxFor vs EditorFor, and htmlAttributes vs additionalViewData - asp.net-mvc-3

I have created a default MVC 3 project (using razor), in order to demonstrate an issue.
On the login page, there is a line:
#Html.TextBoxFor(m => m.UserName)
if I change this to:
#Html.TextBoxFor(m => m.UserName, new { title = "ABC" })
Then the it is rendered as (with a title attribute):
<input data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" title="ABC" type="text" value="" />
However, if I make it an EditorFor:
#Html.EditorFor(m => m.UserName, new { title = "ABC" })
Then it gets rendered (without a title attribute) as:
<input class="text-box single-line" data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" type="text" value="" />
So in summary, the title attribute is lost when I use EditorFor.
I know that the second parameter for TextBoxFor is called htmlAttributes, and for EditorFor it is additionalViewData, however I've seen examples where EditorFor can render attributes supplied with this parameter.
Can anyone please explain what I am doing wrong, and how I can have a title attribute when using EditorFor?

I think I found a little nicer solution to it. EditorFor takes in additionalViewData as a parameter. If you give it a parameter named "htmlAttributes" with the attributes, then we can do interesting things with it:
#Html.EditorFor(model => model.EmailAddress,
new { htmlAttributes = new { #class = "span4",
maxlength = 128,
required = true,
placeholder = "Email Address",
title = "A valid email address is required (i.e. user#domain.com)" } })
In the template (in this case, EmailAddress.cshtml) you can then provide a few default attributes:
#Html.TextBox("",
ViewData.TemplateInfo.FormattedModelValue,
Html.MergeHtmlAttributes(new { type = "email" }))
The magic comes together through this helper method:
public static IDictionary<string, object> MergeHtmlAttributes<TModel>(this HtmlHelper<TModel> htmlHelper, object htmlAttributes)
{
var attributes = htmlHelper.ViewData.ContainsKey("htmlAttributes")
? HtmlHelper.AnonymousObjectToHtmlAttributes(htmlHelper.ViewData["htmlAttributes"])
: new RouteValueDictionary();
if (htmlAttributes != null)
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
var key = property.Name.Replace('_', '-');
if (!attributes.ContainsKey(key))
{
attributes.Add(key, property.GetValue(htmlAttributes));
}
}
}
return attributes;
}
Of course you could modify it to render the attributes as well if you are doing raw HTML:
public static MvcHtmlString RenderHtmlAttributes<TModel>(this HtmlHelper<TModel> htmlHelper, object htmlAttributes)
{
var attributes = htmlHelper.ViewData.ContainsKey("htmlAttributes")
? HtmlHelper.AnonymousObjectToHtmlAttributes(htmlHelper.ViewData["htmlAttributes"])
: new RouteValueDictionary();
if (htmlAttributes != null)
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
var key = property.Name.Replace('_', '-');
if (!attributes.ContainsKey(key))
{
attributes.Add(key, property.GetValue(htmlAttributes));
}
}
}
return MvcHtmlString.Create(String.Join(" ",
attributes.Keys.Select(key =>
String.Format("{0}=\"{1}\"", key, htmlHelper.Encode(attributes[key])))));
}

In MVC3 you can add a title (and other htmlAttributes) using this kind of workaround if you create a custom EditorFor template. This case is prepared for the value to be optional, editorFor calls are not required to include the object additionalViewData
#Html.EditorFor(m => m.UserName, "CustomTemplate", new { title = "ABC" })
EditorTemplates/CustomTemplate.cshtml
#{
string s = "";
if (ViewData["title"] != null) {
// The ViewData["name"] is the name of the property in the addtionalViewData...
s = ViewData["title"].ToString();
}
}
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { title = s })
I did something very similar to include an optional class in an EditorTemplate. You can add as many items to the addtionalViewData as you like but you need to handle each on in the EditorFor template.

You may take a look at the following blog post which illustrates how to implement a custom metadata provider and use data annotations on your view model in order to define html properties such as class, maxlength, title, ... This could then be used in conjunction with the templated helpers.

Related

MVC Validate At Least One Checkbox Or a Textbox is Selected

I have a form where either at least one checkbox must be checked OR a textbox is filled in.
I have a ViewModel that populates the CheckboxList and takes the selected values plus the textbox (other) value when required to a SelectedWasteTypes property within the ViewModel. I think my problem is I can't validate against this property as there is no form element on the view that directly relates to it. I've very new to MVC and this one has stumped me.
From the ViewModel
public List<tblWasteTypeWeb> WasteTypeWebs { get; set; }
public string WasteTypeWebOther { get; set; }
public string SelectedWasteTypes { get; set; }
View (segment)
#using (Html.BeginForm("OrderComplete", "Home"))
{
//Lots of other form elements
#for (var i = 0; i < Model.WasteTypeWebs.Count; i++)
{
var wt = Model.WasteTypeWebs[i];
#Html.LabelFor(x => x.WasteTypeWebs[i].WasteTypeWeb, wt.WasteTypeWeb)
#Html.HiddenFor(x => x.WasteTypeWebs[i].WasteTypeWebId)
#Html.HiddenFor(x => x.WasteTypeWebs[i].WasteTypeWeb)
#Html.CheckBoxFor(x => x.WasteTypeWebs[i].WasteTypeWebCb)
}
<br />
<span>
#Html.Label("Other")
#Html.TextBoxFor(x => x.WasteTypeWebOther, new { #class = "form-control input-sm" })
</span>
//More form elements
<input type="submit" value="submit" />
}
Controller Logic (if you can call it that)
[HttpPost]
public ActionResult OrderComplete(OrderViewModel model)
{
var sb = new StringBuilder();
if (model.WasteTypeWebs.Count(x => x.WasteTypeWebCb) != 0)
{
foreach (var cb in model.WasteTypeWebs)
{
if (cb.WasteTypeWebCb)
{
sb.Append(cb.WasteTypeWeb + ", ");
}
}
sb.Remove(sb.ToString().LastIndexOf(",", StringComparison.Ordinal), 1);
}
model.SelectedWasteTypes = sb.ToString();
if (!string.IsNullOrEmpty(model.WasteTypeWebOther))
{
if (!string.IsNullOrEmpty(model.SelectedWasteTypes))
{
model.SelectedWasteTypes = model.SelectedWasteTypes.TrimEnd() + ", " + model.WasteTypeWebOther;
}
else
{
model.SelectedWasteTypes = model.WasteTypeWebOther;
}
}
return View(model);
}
I very much feel I'm up a certain creek... I've thought about using JQuery, but ideally I'd like server side validation to be sure this info is captured (its a legal requirement). However, if this can only be achieved client side, I will live with it.
Any suggestions?
Take a look at the MVC Foolproof Validation Library. It has validation attributes for what you are trying to accomplish: [RequiredIfEmpty] and [RequiredIfNotEmpty]. You can also take a look at my previous SO answer about Conditional Validation.
I would suggest you to implement IValidatableObject in your ViewModel.
Inside Validate( ValidationContext validationContext) method you can check weather your conditions are met. For example:
if(string.IsNullOrWhiteSpace(WasteTypeWebOther))
yield return new ValidationResult("Your validation error here.");

mvc3, editor template, css clas, maxlength and size

I have an editor template as following but class, maxlength and size attributes are not getting to the source.
#using System.Globalization
#model DateTime?
#Html.TextBox("", (Model != null && Model.HasValue && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("1900") && !Model.Value.ToString(CultureInfo.InvariantCulture).Contains("0001") ? Model.Value.ToString("MM/dd/yyyy") : string.Empty), new { #class = "datePicker", maxlength = "12", size = "12" })
I have changed it to following and it is still the same
#Html.EditorFor(x => x.Criteria.FromDate, new { #class = "datePicker", maxlength = "12", size = "12" })
Source
<input class="text-box single-line" id="Criteria_FromDate" name="Criteria.FromDate" type="text" value="" />
How can i fix this?
Make sure your Editor template is named DateTime - placed in folder Views/Shared/EditorTemplates, and your model (Criteria.FormDate) is same type as EditorTemplate model (DateTime?).
If all DateTime fields will have same maxlength and size you can keep them hardcoded in your EditorTemplate.
Example for your html:
#EditorFor(x => x.Criteria.FormDate) //no need to pass html attributes object if they are not used in the editor template
-- its worth trying #EditorFor(model, "EditorTemplateName") to explicitly say you want that TemplateEditor for passed model. This is the case when you have multiple editors for same model type, so you call them explicitly(works like calling partial view and passing model to it).
EDIT:
After looking at your template, it seems to me that your Criteria.FormDate is non nullable. You should look at improving/refactoring your code in template.

pass data-icon attributes in razor html helper

I want to following html code using asp.net mvc 3 razor html helper:
<input type="text" .... . placeholder="Login" data-icon="user" />
I have try this one:
#Html.TextBoxFor(m => m.UserName, new { placeholder = "Login", data-icon = "user" })
or
#Html.TextBoxFor(m => m.UserName, new { placeholder = "Login", #data-icon = "user" })
Displayed Error:
Invalid anonymous type members declaration.
This might due to dash in data-icon not taken as attributes. How could I add data-icon attributes in text box field.
try this
#Html.TextBoxFor(m => m.UserName, new { placeholder = "Login", data_icon = "user" })
Yes, you can't write like that but you can write your own Extension to solve this problem. Here is the sample code:
public static MvcHtmlString MyInput(this HtmlHelper htmlHelper, string name, string value, string icon)
{
var attrs = new Dictionary<string,object>();
attrs.Add("data-icon", icon);
return htmlHelper.TextBox(name, name, value, attrs);
}
Or you can also use in razor like this:
#{
var attrs = new Dictionary<string, object>();
attrs.Add("placeholder","Login");
attrs.Add("data-icon","user");
}
#Html.TextBoxFor(m => m.UserName, attrs)
Plz don't forget to mark it's right answer if it helps you :-)
This is really the same as vNext's second alternative, but if you prefer to write it in-line:
#Html.TextBoxFor(m => m.UserName, new Dictionary<string, object> { { "placeholder", "Login" }, { "data-icon", "user" } })

MVC 3 Get result from partial view into model

I'm sure this is easy, but maybe I haven't searched well ...
I want to know how to get results from a partial view back to the model and/or controller.
If the user enters a FirstName, Gender (from drop down) and Grade (from drop down), I only find then FirstName and Gender in the model. I want to know how to get the Grade from the drop down in the partial view all the way back into the model, so I can see it in the controller.
Please look for this question in the controller code:
What do I need to do to get the GradeLevel from the partial class to be here: <<<<<
Note: this is not the exact code. There may be small, insignificant typo's.
EDIT: Apparently you can't add a long comment, so I will add here:
Thank you, Tom and Mystere Man. Tom got me thinking as to why it doesn't work. I didn't think through the model binding. With the design I proposed, the HTML gets rendered and the Grade drop down has this id: "Grade". The property on the model I want to bind to is: "GradeLevelID". If I change the helper in the partial view to be #Html.DropDownList("GradeLevelID" ... it works perfectly.
But that is not a good solution. My idea was to abstract the partial view from the main view. Hard coding the name blows that! I did work up a slightly improved solution. In the main view, I change the #Html.Partial statement to pass the model property name to the partial. Like such:
#Html.Partial("GradeDropDown", (SelectList)Model.GradeSelectList, new ViewDataDictionary { { "modelPropertyName", "GradeLevelID" } })
Then I could change the partial view to say
#model System.Web.Mvc.SelectList
#Html.DropDownList((string)ViewData["modelPropertyName"], Model)
But that also seems like a goofy way to approach things. Thanks for the help. I'll look at EditorTemplates.
Here is my model:
public class RegisterModel{
public MemberRegistration MemberRegistration{
get{
if (HttpContext.Current.Session["MemberRegistration"] == null){
return null;
}
return (MemberRegistration)HttpContext.Current.Session["MemberRegistration"];
}
set{
HttpContext.Current.Session["MemberRegistration"] = value;
}
}
public string FirstName{
get{
return MemberRegistration.FirstName;
}
set{
MemberRegistration.FirstName = value;
}
}
public SelectList GenderSelectList{
get{
List<object> tempList = new List<object>();
tempList.Add(new { Value = "", Text = "" });
tempList.Add(new { Value = "M", Text = "Male" });
tempList.Add(new { Value = "F", Text = "Female" });
return new SelectList(tempList, "value", "text", MemberRegistration.Gender);
}
}
[Required(ErrorMessage = "Gender is required")]
public string Gender{
get{
return MemberRegistration.MemberPerson.Gender;
}
set{
MemberRegistration.MemberPerson.Gender = value;
}
}
public SelectList GradeLevelSelectList{
get{
List<object> tempList = new List<object>();
tempList.Add(new { Value = "", Text = "" });
tempList.Add(new { Value = "1", Text = "1st" });
tempList.Add(new { Value = "2", Text = "2nd" });
tempList.Add(new { Value = "3", Text = "3rd" });
tempList.Add(new { Value = "4", Text = "4th" });
return new SelectList(tempList, "value", "text", MemberRegistration.GradeLevel);
}
}
[Required(ErrorMessage = "Grade is required")]
public Int32 GradeLevel{
get{
return MemberRegistration.GradeLevel;
}
set{
MemberRegistration.GradeLevel = value;
}
}
}
Here is my main view:
#model RegisterModel
#using (Html.BeginForm())
{
<p class="DataPrompt">
<span class="BasicLabel">First Name:</span>
<br />
#Html.EditorFor(x => x.FirstName)
</p>
<p class="DataPrompt">
<span class="BasicLabel">Gender:</span>
<br />
#Html.DropDownListFor(x => x.Gender, Model.GenderSelectList)
</p>
<p class="DataPrompt">
<span class="BasicLabel">Grade:</span><span class="Required">*</span>
<br />
#Html.Partial("GradeDropDown", (SelectList)Model.GradeLevelSelectList)
</p>
<p class="DataPrompt">
<input type="submit" name="button" value="Next" />
</p>
}
Here is my partial view (named "GradeDropDown"):
#model System.Web.Mvc.SelectList
#Html.DropDownList("Grade", Model)
Here is my controller:
[HttpPost]
public ActionResult PlayerInfo(RegisterModel model)
{
string FirstName = model.Registration.FirstName;
string Gender = model.Registration.Gender;
>>>>> What do I need to do to get the GradeLevel from the partial class to be here: <<<<<
Int32 GradeLevel = model.Registration.GradeLevel;
return RedirectToAction("Waivers");
}
I don't even know why you are using a partial view. All you're doing is using one helper method, you could replace the partial view with the helper method in the view and it would be less code.
Second, you should be using Html.DropDownListFor() instead of Html.DropDownList(), then it will correctly name the html controls for you.
Just do this:
<p class="DataPrompt">
<span class="BasicLabel">Grade:</span><span class="Required">*</span>
<br />
#Html.DropDownListFor(m => m.GradeLevel, (SelectList)Model.GradeLevelSelectList)
</p>
try this to get the correct naming for the elements when they get posted.
On your main view
#Html.Partial("GradeDropDown", Model) //Pass the Model to the partial view
Here is your partial view (named "GradeDropDown"):
#model RegisterModel
#Html.DropDownList("Grade", (SelectList)Model.GradeLevelSelectList)

ASP.NET MVC 3 - Data Annoation and Max Length/Size for Textbox Rendering

I know on the Razor View file, we can do something like this
#Html.TextBox("username", null, new { maxlength = 20, autocomplete = "off" })
However, I am hoping to create a model for the MVC that can be used to create a form with explicitly defined the size and max length of the textboxes. I try [StringLength(n)] on top of the properties of the model, but that seems to only do the validation ratherh set the size of the textbox.
Is there anyway that we can define the length of the text field as a data annotation on top of a property of a model?
So ultimately, we could just create the whole form by using razor to map to a model rather than explicitly pick up the model properties one by one in order to set the textbox size.
Here is a outline of a custom helper that uses StringLengthAttribute.
public class MyModel
{
[StringLength(50)]
public string Name{get; set;}
}
public MvcHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
var attributes = new Dictionary<string, Object>();
var memberAccessExpression = (MemberExpression)expression.Body;
var stringLengthAttribs = memberAccessExpression.Member.GetCustomAttributes(
typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true);
if (stringLengthAttribs.Length > 0)
{
var length = ((StringLengthAttribute)stringLengthAttribs[0]).MaximumLength;
if (length > 0)
{
attributes.Add("size", length);
attributes.Add("maxlength", length);
}
}
return helper.TextBoxFor(expression, attributes);
}
Does this not work?
public class ViewModel
{
[StringLength(20)]
public string UserName {get;set;}
}
In the View:
#Html.TextBoxFor(x => x.UserName, new {autocomplete = "off"})
or:
#Html.EditorFor(x => x.UserName)
I find that I prefer my views to just Call Html.EditorFor(...). This means that the Editor and Display templates decide the fate of controls in my view, such that my view code gets cleaned up a lot - it just has html and generic requests for editors.
The following link gives a working sample of getting this working in an Editor Template
https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/
I'm using similar in my String.cshtml Editor Template (goes in Shared/EditorTemplates ).
#model object
#using System.ComponentModel.DataAnnotations
#{
ModelMetadata meta = ViewData.ModelMetadata;
Type tModel = meta.ContainerType.GetProperty(meta.PropertyName).PropertyType;
}
#if(typeof(string).IsAssignableFrom(tModel)) {
var htmlOptions = new System.Collections.Generic.Dictionary<string, object>();
var stringLengthAttribute = (StringLengthAttributeAdapter)ViewData.ModelMetadata.GetValidators(this.ViewContext.Controller.ControllerContext).Where(v => v is StringLengthAttributeAdapter).FirstOrDefault();
if (stringLengthAttribute != null && stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"] != null)
{
int maxLength = (int)stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"];
htmlOptions.Add("maxlength", maxLength);
if (maxLength < 20)
{
htmlOptions.Add("size", maxLength);
}
}
htmlOptions.Add("class", "regular-field");
<text>
#Html.TextBoxFor(m => m, htmlOptions)
</text>
}
else if(typeof(Enum).IsAssignableFrom(tModel)) {
//Show a Drop down for an enum using:
//Enum.GetValues(tModel)
//This is beyond this article
}
//Do other things for other types...
Then my model is annotated such as:
[Display(Name = "Some Field", Description = "Description of Some Field")]
[StringLength(maximumLength: 40, ErrorMessage = "{0} max length {1}.")]
public string someField{ get; set; }
And my View simply calls:
<div class="editor-label">
#Html.LabelWithTooltipFor(model => model.something.someField)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.something.someField)
#Html.ValidationMessageFor(model => model.something.someField)
</div>
You might also notice that my String.cshtml Editor Template also auto-magically handles Enum's, but that is starting to digress from the current topic, so I nixed that code, I'll just say here that the String Editor Template can pull extra weight, and likely google has someting on that https://www.google.com/search?q=string+editor+template+enum
Label With Tooltip For is a custom HTML helper that just drops the description into the label title, for more information on mouse over for every label.
I'd recommend this approach if you want to do this in an Editor Template.

Resources