Razor #Html.ValidationMessageFor() not displaying "validation error message" - c#

#Html.RequiredLabelFor(x => x.FirstName)
#Html.TextBoxFor(model => model.FirstName, new { Name = "1.first_name", tabindex = "1" })
#Html.ValidationMessageFor(model => model.FirstName)
Is there a reason why when passing second parameter to #Html.TextBoxFor the field is being validated but "validation message" does not appear?
#Html.RequiredLabelFor(x => x.FirstName)
#Html.TextBoxFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
When using an overload that accepts only one argument (lambda expression) "validation message" is being displayed correctly.
In my understanding the actual property is not being recognized?
Backing property:
[StringLength(100, ErrorMessage = "Max length 100 characters")]
[Required(ErrorMessage = "This field is required")]
[Display(Name = "First name")]
public string FirstName { get; set; }

The unobtrusive validation library identifies 'things to display validation for' using the name attribute. It's not that specifying extra properties stops it from working, but you have changed the name property and not reflected the new name in your validation helper.
You can either stop changing the name attribute in your textbox helper (necessary if you use the default model binder to return your view), or you can use
#Html.ValidationMessage("1.first_name")
The above method is not a good idea unless you're using JS/JQuery to validate and submit your form data (via AJAX), for the reasons given by Stephen in comment to this answer.

You have changed the name attribute, so not only will it not post back and bind to your model, jquery.validate.unobtrusive can now no longer match up the controls since the input has a different name than the associated validation message
<input name="1.first_name" ... />
<span .. data-valmsg-for="FirstName" ..></span> // There is no control named FirstName

Related

Working with password field in mvc

Whenever I am trying to insert records it gives me error message for password field as '
The value 'SomePassword' is not valid for password
Model
public byte[] Password { get; set; }
View
<label class="input">
<i class="icon-append fa fa-tag"></i>
#Html.PasswordFor(model => model.Class.Password, new { #class = "form-control", #id = "txtPassword" })
<span asp-validation-for="Class.Password" class="text-danger"></span>
</label>
When checked in controller the ModelState is invalid and error message is coming why is it so ?. I have tried with DataType.Password on Password field, but still no success
The Password column has datatype 'Varbinary' in sql server.
Any help on this appreciated !
A password is never entered by the user as a byte arrray, it is converted into one before hashing.
The mvc model binder has no built in capability to convert any input to a byte array, and even though you could write a custom model binder I don't see why you would want to, as a plain string is much easier to type.
Even though the SQL type may be varbinary, you do not want the user to enter this representation in your model.
You should set the Class.Password property to be a string, and then in your server side code, you should be hashing the password.
Encoding.UTF8.GetBytes(password); will convert the string password into a byte[] but it on it's own it is not sufficient for secure password storage.
I strongly recommend you take a look at https://www.asp.net/identity if you have the option to upgrade your password requriements.
why dont you start with the Password model of the Default Account, and modify it to fit your actual need? or you have a very unusal password requirement which need byte[]? otherwise you should just convert it when you actually needed to...
Model
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
View
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
What you wrote would only work if class Model has a property called Class, and the property Class has a property Password.
Try using this instead:
#Html.PasswordFor(model => model.Password, ...
Also, the Password property in your ViewModel needs to be a string. Both the Web and MVC cannot use byte[] for text input controls.
You can store a byte[] - hashed and encrypted, the best approach! - but it first comes in as a string.

Concatenate string to Display Culture Value MVC 4+

Hi I've followed the following post in order to localize labels for a form.
http://afana.me/post/aspnet-mvc-internationalization.aspx
I works perfectly but I'm trying to find a way to concatenate ":" on to the display value (i.e. Address:)?
View:
<div class="col-sm-5">
#Html.LabelFor(model => model.Address)
</div>
Model:
[Required]
[Display(Name = "Address", ResourceType = typeof(Resources.Resources))]
public string Name { get; set; }
key in resx file
Name :Address
Value:Address
My attempts are:
Change the model
[Display(Name = "Address" + ":", ResourceType = typeof(Resources.Resources))]
Change the view
#Html.LabelFor(model => model.Address, Name + ":")
Anyone with any ideas if it's possible? Is there away to get the Name property and manipulate it in the view?
https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute%28v=vs.110%29.aspx
I would prefer to keep it simple and see the View changed by adding, for example, :.
The text "Address" is bound to be used somewhere else where a colon or dash isn't required.

harvest chosen plugin fails to show validation messages for asp.net mvc dropdown list

I am unable to get validation messages after changing my dropdownlist to chosen dropdown list. Chosen plugin can be found here
Jquery code
$('#SelectedPropertyGroup').chosen();
UI Code
<div>
#Html.DropDownListFor(x => x.SelectedGroup, Model.Groups, "Select Group", new
{
#onchange = "javascript:ValidateApplicationSelection(this, 'Group');",
#placeholder = "Please select a product"
})
</div>
<div>
#Html.ValidationMessageFor(model => model.SelectedGroup, "", new { id = "valGroup" })
</div>
Model Code
[Required(ErrorMessage = "Select Group")]
[DisplayName("Group: ")]
public string SelectedGroup { get; set; }
The client side validation ignores hidden fields by default -- Chosen hides the "real" select element when it applies it's magic. You can change the validator defaults like so:
$.validator.setDefaults({ ignore: ":hidden:not(select)" });
This will set the validator to ignore any hidden fields that aren't select elements.
The default for the ignore is ":hidden"

C# MVC property name to HTML id

I know that I could do this manually, but is there a built in function to convert a C# MVC Razor property name to the value that Razor will use as the HTML id?
To expand on this question:
I am trying to access the HTML element using JavaScript in a partial view. (The partial view means that I do not have access to the parameter name directly.)
The following two partial solutions double up the ID, giving you ParameterName_ParameterName:
string name = ViewData.TemplateInfo.HtmlFieldPrefix
#Html.Id(name)
#ViewData.TemplateInfo.GetFullHtmlFieldId(name)
The solution I'm going with at the moment:
Regex.Replace(name, #"[\.\[\]]", "_");
I guess you could add parentheses.
As per your comments:
IMHO you should not be using your model in that fashion. If you need access to children objects, create a new model and bind to it that exposes that directly. Then in your controller piece back together your original model as needed. In the case of a Registration Form, if its highly complex, try breaking it up in to smaller pieces (seperate views), otherwise use a flat model that combines all the fields like Username, Password, etc then assign values to the appropriate objects.
Remember that the least amount of complexity is the better solution, as it improves maintainability.
When you define a moldel
something like this
public class AnnonymousModel
{
[Required]
[StringLength(20, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 3)]
[Display(Name = "User name")]
[RegularExpression(#"^[A-Za-z\n\r\0-9_ ]+$")]
public String RegisterUsername {get; set;}
}
and then use it in mvc view page
For Razor
#Html.TextBoxFor(m => m.RegisterUsername, new { #class = "inp-form", #placeholder = "User name" })
For asp
<%Html.TextBoxFor(m => m.RegisterUsername, new { #class = "inp-form", #placeholder = "User name" })%>
the in the Html renderd is like this
<input type="text" value="" placeholder="User name" name="RegisterUsername"
id="RegisterUsername" data-val-required="The User name field is required." data-val-regex-
pattern="^[A-Za-z\n\r\0-9_ ]+$" data-val-regex="The field User name must match the regular
expression '^[A-Za-z\n\r\0-9_ ]+$'." data-val-length-min="3" data-val-length-max="20"
data-val-length="The User name must be at least 3 characters long." data-val="true"
class="inp-form">
So the Id is automatically generated as the property name specified.

MVC 3 show required , regular expression validation on different location

I have made both Required and Regular Expression validation working.
the only problem is i want to show them both on different location within the page.
just like the required validation message will be shown before the textbox. the regular expression validation message will be shown after the textbox. How can i do it?
Here is my model code
[Required(ErrorMessage = "*")]
[RegularExpression(#"^[\w-]+(?:\.[\w-]+)*#(?:[\w-]+\.)+[a-zA-Z]{2,7}$", ErrorMessage = "Invalid Email")]
public string Email { get; set; }
Here is my View code
#Html.ValidationMessageFor(p => p.Email)
#Html.TextBoxFor(p => p.Email)
#Html.LabelFor(p => p.Email, "Email")
On the above code, both error messages will show before the textbox, i want to make something like this
#Html.ValidationMessageFor(p => p.Email) - required validation message which is "*"
#Html.TextBoxFor(p => p.Email)
#Html.LabelFor(p => p.Email, "Email")
#Html.ValidationMessageFor(p => p.Email) - regular expression validation message which is "Invalid Email"
There is nothing out of the box that would give you fine grain control over individual validation errors for a single control. You would need to manually parse the individual errors from the ModelState - see this example.

Categories

Resources