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 )
Related
I am trying to populate #Html.EditorFor helper. I have created a view model with the below property
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yy}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }
and my helper is set up as below (a)
#Html.ValidationMessageFor(m => m.YearBought)
#Html.EditorFor(model => model.YearBought, new { #type = "date" })
I have also tried (b)
#Html.ValidationMessageFor(m => m.YearBought)
#Html.EditorFor(model => model.YearBought.Value.Date)
Using the above format (a) nothing is displayed. Using the above format (b) 12/05/2014 00:00:00 is displayed in textbox format.
I am trying to achieve a datepicker format without a time displayed
I have reviewed several other questions but cant see what i've done different.
When I look in my database, the value is save as 2014-05-12 and when I am saving the value the EditorFor helper generates the required input facility
questions reviewed
first second third....the list goes on
EDIT
just opened the console in chrome dev tools and so this message
The specified value "12/05/14" does not conform to the required format, "yyyy-MM-dd"
I thought DisplayFormat(DataFormatString = "{0:dd/MM/yy}" was defining how to display my date?
You need to use the ISO format when using type="date"
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }
This will display the date in the browsers culture.
Note there is no need to add #type = "date". The EditorFor() method will add that because of the DataType attribute. Note also that type="date" is only supported in Chrome (FireFox and IE will just generate a normal textbox)
If you do want to display the format dd/MM/yyyy in a standard textbox then you can use
#Html.TextBoxFor(m => m.YearBought, "{0:dd/MM/yyyy}")
As it says in Stephen's answer, you have to make your formats match between the tags in your model to what is shown in the View, and it should be of the yyyy-MM-dd (ISO) format, regardless of how you actually want to display the date:
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
// .... your namespace .... your class....
[DisplayName("Year Bought")]
[DataType(DataType.Date, ErrorMessage="Date only")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? YearBought { get; set; }
And he's right, because we have [DataType(DataType.Date)], we don't need #type = date in our HtmlAttributes on the View.
Where my answer differs from his is how to actually apply the value from the Model to the control on the View. Since YearBought is a Nullable<DateTime>, we have to set it with its value a certain way, using .Value:
#Html.EditorFor(model => model.YearBought,
new { htmlAttributes = new { #class = "form-control datepicker",
#Value = Model.YearBought.Value.Date.ToString("yyyy-MM-dd") } })
Paying close attention to set the .ToString("yyyy-MM-dd"). It's not going to display in the box like that, though - at least for me - probably because my U.S. Regional settings on my computer take over and display it as MM/dd/yyyy regardless. This might confuse some, but it's better to just "do" and not worry about it.
If YearBought was just a straight DateTime instead of a DateTime?, it would be without the .Value:
#Html.EditorFor(model => model.YearBought,
new { htmlAttributes = new { #class = "form-control datepicker",
#Value = Model.YearBought != null ?
Model.YearBought.Value.Date.ToString("yyyy-MM-dd") : null } })
I would make your view model's YearBought property a String for the easiest manipulation. The server can format the date, it can do the parsing on postback, and you can still use the DataType.Date data annotation for jQuery validation. This also ensures that the display value will be exactly what you want prior to being submitted to the view.
Alternative to the HTML type attribute, you can use an EditorTemplate in MVC to put the markup, CSS, and JS needed to render a custom editor for a known C# datatype like DateTime.
Here is a walkthrough for creating a custom 'EditorTemplate' in MVC (although not for a Date data type, but concept is the same)
I'm currently using autoNumeric in my application.
It works great.
However, in edit mode, JQuery is showing this error message:
The value ($ 100.000.00) being 'set' is not numeric and has caused a error to be thrown
I've something like this:
public string Amount { get; set; }
#Html.TextBoxFor(model => model.Amount, new { #class = "form-control", #placeholder = ModelMetadata.FromLambdaExpression(x => x.Amount, ViewData).Watermark })
$.extend($.fn.autoNumeric.defaults, {
aSep: '#System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator',
aDec: '#System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator'
});
$("#Amount").autoNumeric('init', { aSign: "$ " });
I have search for the error and found this
but that didn't help me.
Thanks for the help!
When I enter the value, during creation it is entered as $ 100,000.00
and that is save to the database just like that.
However, I have updated my code to remove the symbols before saving.
var amount = String.Join("", model.Amount.Split('$', ','));
So if $ 100,000.00 is entered, it is saved as 100000.00
and that fixed the issue.
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.
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.
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.