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.
Related
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.
#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
I have a required string for my model and I can submit the form and still leave the textbox blank and the model state is being returned as valid so I have no idea what I did wrong. This is the only control on my page that is doing this. Here is my code:
Model
[Required(ErrorMessage = "Requirements are Required.")]
[DataType(DataType.MultilineText, ErrorMessage = "Requirements is Required.")]
[StringLength(200, ErrorMessage = "200 Characters is the maximum allowed for requirements.")]
public string Requirements { get; set; }
View
<div class="form-group">
#Html.LabelFor(model => model.Requirements, "Requirements:", htmlAttributes: new { #class = "col-sm-4 control-label" })
<div class="col-sm-8">
#Html.TextAreaFor(model => model.Requirements, htmlAttributes: new { #rows = "10", #cols = "50", #class = "form-control" })
#Html.ValidationMessageFor(model => model.Requirements)
</div>
Edit:
As #Stephen Muecke noted, I cant reproduce your case neither, it should be enough Required attribute.
My answer below somehow Workaround as said by #MajkeloDev.
You should put MinimumLength = 10 for your field. number 200 indicates maximum length for your string
[StringLength(200, MinimumLength = 10, ErrorMessage = "200 Characters is the maximum allowed for requirements.")]
Note: MinimumLength = 10 is being some number for a meaningful input. For non empty string it is enough MinimumLength = 1
I am developing a ASP.NET MVC 5 website. I have the Employee model which looks something like this:
public class Employee
{
public EmployeeID {get;set;}
//... other properties such as FirstName, Salary which are not important right now
public DateTime? EndingDate {get; set;} //this is important
}
The corresponding part of the view is like this:
<div class="form-group">
#Html.LabelFor(model => model.EndingDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="endingDate" type="date" class="form-control datepicker" />
#Html.ValidationMessageFor(model => model.EndingDate, "", new { #class = "text-danger" })
</div>
</div>
As you can see the EndingDate is nullable because I do not necessarily fill the EndingDate field. If I want to create an employee without filling the EndingDate I get a validation error, which makes sense because on the datepicker the value is exactly the following dd.mm.yyy. This happens on Google Chrome. On Mozilla it is null by default but is behaving like a textbox not like a datepicker. I am using bootstrapper css classes, I didn't wrote a single line of front-end development code; if you accept the language. I tried to add to model the DisplayFormat attribute but no success so far.
Any ideas? Or it is a matter of browsers?
At this point a don't know any method. You can try a text box where you will fill the data and validate it in a dynamic way (using Angular by chance). Think about filing a data from a dumb phone. You enter the digits and it feels the data.
dateTimePicker1.CustomFormat= " ";
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.