Concatenate string to Display Culture Value MVC 4+ - c#

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.

Related

I want to let my text box allow only text

I'm working on project using MVC3 + Razor.I want to let my text box allow only text. I tried to apply data annotation in my data model (First Code):
[DataType(DataType.Text ,ErrorMessage ="Error")]
but, it's not working.Could anyone help me ?
You need a regular expression as below:
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Please input letters only")]
You could annotate your model like this:
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Use letters only please")]
string TextBoxData {get; set;}
Then in your view you would use the helper
#Html.EditorFor(model => model.TextBoxData)
#Html.ValidationMessageFor(model => model.TextBoxData )

Binding lost on #Html.EditorFor when I apply formatting

When using the following I lose the binding on the field
#Html.EditorFor(model => model.Quote.DiscountRate, new { #class = "form-control pull-left " })
And the model field looks like this:
[DisplayFormat(DataFormatString = "{0:P2}",ApplyFormatInEditMode =true)]
public double? DiscountRate { get; set; }
if I remove the DisplayFormat the binding still works.
I also tried the following with the same result:
#Html.TextBoxFor(model => model.Entity.DiscountRate, "{0:P2}", new { #class = "form-control pull-left" })
In both cases if I remove the formatting I get my binding back
What I have discovered is that when you apply a DisplayFormat, it is as the name suggests, for display. If you want to display a decimal value with formatting and make it available for editing, you have to handle the conversion from text back to decimal at post time -- or whenever you need the actual value.

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.

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

#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

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.

Categories

Resources