Asp.net MVC Html.TextboxFor title and validation message conflict - asp.net-mvc-3

I have a Asp.net MVC application(using Razor View) in which i am using Html.Textboxfor for textbox. Below is the code :
#Html.TextBoxFor(m => m.Textbox1, Model.Attributes)
The attributes i am adding for these are
Model.Attributes = new Dictionary<string,object>);
Model.Attributes .Add("size", "3");
Model.Attributes .Add("min", 0);
Model.Attributes .Add("max", 100);
Model.Attributes .Add("title", "Value");
So when i click on submit i am validating the Textbox and it shows the default title as error message when data outside the specified range is entered. Any way to prevent this from happening and add a custom error message different from title?

im not sure what u try to do but i think u need just use data anotation
[StringLength(100, MinimumLength=1, ErrorMessage = "error message here")]
public string title { get; set; }

Related

Required validation on hidden field

I am using client side validation on hidden field in asp.net MVC. I am using required validation using data annotations. I am trying to validate hidden field but it’s not working.
My Model
[Required(ErrorMessage = "From date is required")]
public DateTime? FromDate { get; set; }
My View
#Html.HiddenFor(m => m.FromDate, new { ID = "hfdFromDate" }
#Html.ValidationMessageFor(m => m.FromDate)
I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.
Thanks in advance.
As some have pointed the validation isn't performed because the "hidden" property is set.
I had the same issue and ended up using the style tag:
#Html.TextBoxFor(m => m.Foo, new { style = "visibility:hidden"})
The validation is then performed.
Added this line before form.valid().
form.data("validator").settings.ignore = "";
where form is your form element.
In my case :
var form = $("#myForm");

DropdownList Data Annotation does not fire when the Textboxes and other controls are firing

I have a form that has several controls in it. I added data annotation to display an error message to the user when the required field are left empty. The TextBoxes and other controls display the message, which is an "*" before the label name, but the dropdownlist does not not. Once the user get rid of all the error messages and click on submit again, then, the message for the dropdown box is display. How do I force the dropdown box to display the message at the same time with the textbox?
Additional information:
Here is a sample of my data annotation:
[MetadataType(typeof(UserMetaData))]
public partial class UserMeta
{
}
public class UserMetaData
{
[Required(ErrorMessage = "*")]
public int GenderID { get; set; }
//The gender ID is displayed in a dropdown
list with "Select" as the default option. Then, it has all the other genders
showing in the dropdown once it is clicked on.
[Required(ErrorMessage = "*")]
public DateTime DataOfBirth{ get; set; }
}
In my view, I am using
#Html.ValidationMessageFor(model => model.DataOfBirth) //This is working fine.
#Html.ValidationMessageFor(model => model.GenderID)
//Here is the dropdown
#Html.DropDownList("GenderID", null, "Select", new { style = "width:200px;", onchange = "ValidateDropdown()" })
//This is the one that is not working as expected. I could get it to work using javascript, but I am trying not to it if I there is a way to get it to work properly using data annotation.
Thank in advance for your help.
I could not get it to work properly on the server side. As a result, I had to write a JQuery function that does the validation for the dropdown on the client side. Then, I do the post only if there is a selection on the dropdown.

how to bind model property to html helper textboxfor in mvc3

i want to tightly bind my property using html helper for TextBoxFor but i am not able to do so,i have simply binded using Textbox but i want to get data assign to textbox on httpPost
below is how i have done using simple HtmlHelper textbox
<%: Html.TextBox("RenewalDate", (string.Format("{0:yyyy/MM/dd}", Model.RenewalDate)), new { id = "txtRenewalDate", maxlength = 20, tabindex = 3, #class = "date" })%>
i dont want to use FormCollection that's why i want to bind tightly with TextBoxFor so that on httpPost my model has the value assigned to the Model.RenewalDate
please help....
Use an editor template, it's much easier:
<%= Html.EditorFor(x => x.RenewalDate) %>
and you could decorate your view model property with the DisplayFormat attribute to specify the desired format:
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime RenewalDate { get; set; }
and then your POST controller action will take the view model as action parameter.
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
...
}
And in order to apply the HTML attributes such as class, tabindex and maxlength to this editor template you could write a custom metadata provider as shown in the following article.
Also since the date is using the yyyy/MM/dd it is possible that the default model binder is not able to parse the value back because the default model binder uses the current culture settings. To resolve this issue you could write a custom model binder as I showed in this thread.

EditorTemplate for "Floats" not being called in ASP.NET MVC 3

I have a property of type "float" in my ViewModel. It's being displayed as a TextBox with a default value of "0".
I added an "EditorTemplates" folder inside the "Shared" folder & created a new "Float.cshtml" file with the following content:
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue == 0 ? "" : ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line" })
However, still when I run the application, float fields are still being displayed with a default value of 0.
Thanks
UPDATE
I am just trying to see how ASP.NET reacts to custom templates, till now, the engine is not processing my custom template, something similar to:
LatLng.cshtml
#model float
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line "}) Latitude
On the ViewModel,
[UIHint("LatLng")]
public float? Latitude { get; set; }
On the View,
#Html.EditorFor(model => model.Latitude)
Nothing is changing, default template is being used.
Float is not actually a .NET type, it's a C# type. Float maps to System.Single, so you need to create a Single.cshtml and not a Float.cshtml.
You can also get around this by specifying a UIHint attribute on the model data, or by specifying the template to use in your Editor or EditorFor methods.
An easy workaround is if you just set ViewData.TemplateInfo.FormattedModelValue to return a string in the model, so you don't have to do that weird logic on the view. If you need it to post back a new value (for editing purposes), you just have to add some logic in the controller to turn the string back into a float.

mvc 3 view data validation

i'm trying to put DropDownList validation to work.
in model:
[Required(ErrorMessage = "this field is required")]
public int ObjectTypeID { get; set; }
in view:
<div class="editor-field">
#Html.DropDownList("ObjectTypeID", string.Empty)
#Html.ValidationMessageFor(model => model.ObjectTypeID)
</div>
if the user leaves the selection empty i expect client side validation to alarm. but this does not happen.
what can be done?
The behavior of system types is that they must have a value when initalized. An integer has a value of "0". Change your model to accept a nullable int:
public int? ObjectTypeID { get; set; }
Just wondering, but why not use DropDownListFor?
For client side validation to work I think you need to turn on ClientValidationEnabled & UnobtrusiveJavaScriptEnabled in the web.config for your project, I believe you also need to reference the jquery.validate.unobtrusive.min.js script on your page?
1) You are not loading your dropdownlist
2) Use DropDownListFor in order to match validation with ddl

Resources