mvc how to use annotation with input tag - asp.net-mvc-3

Hi I am using MVC 3 with Razor, I am using the below code.
I need to know whether I can use Annotations with this input tag?
<input type="text" id="#endDateName" name="#endDateName" value="#String.Format("{0:MM/dd/yyyy}", endDateValue)" />
I need annotation to check whether a proper date time value has been entered and not any random text.
Thanks in advance
After some help from Amyz,
I have used date picker now, and yes it does not allow characters like a,..z,!##, and so on.
But the problem is it does allow a date like say 02/1212312321/1231231313 this is what I want to prevent now the same can be seen on http://jqueryui.com/demos/datepicker/

Its better to handle this at client side only: for that you can use date picker:
Date Picker
or you can use data annotation like:
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date (ex: 2/14/2011)")]
public DateTime DateTime { get; set; }
The final step is to register the adapter in our global.asax file:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DataTypeAttribute), typeof(DataTypeAttributeAdapter));

Related

How to bind List<String> values to <select> tag in jsp without comma separated values?

First things first-
My Class-
public class StakeHolder{
private String stakeHolderName;
private Date startDate;
private Date endDate;
}
My Controller Request Mapping-
#RequestMapping(value = { "/add" }, method = RequestMethod.GET)
public String addGet(Model model) {
StakeHolder stakeholderObj = new StakeHolder();
//To be selected in drop-down for 'stakeHolderName' attribute of StakeHolder
List<String> organizationList = stakeholderObjService
.getApplicantOrganizations();
model.addAttribute("orgList", organizationList);
model.addAttribute(STAKEHOLDER_OBJ_STRING, stakeholderObj);
return STAKEHOLDER_ADD_VIEW;
}
My JSP code for drop-down -
<form:select path="stakeHolderName" name="stakeHolderSelect"
id="stakeHolderSelect" style="width:220px;" items="${orgList}" >
When i submit the form with any value from drop down I have a server-side validator to verify all the values of attributes. When there is an error in date format it returns to the same page. When the data is correct and submitted again the dropdown value gets binded to my class's 'stakeHolderName' attribute in comma separated format which is not required.
its something like
StakeHolder [stakeHolderName=,TestOrg1,TestOrg1,TestOrg1, startDate=null, endDate=null]
The original values keeps getting appended to the name each and every time it get submitted with a preceding comma. How can I get the value "TestOrg1" just once without any comma?
Appreciate the help.
try to change your drop down code to this in JSP
<form:select path="stakeHolderName">
<form:options items="${orgList}" />
</form:select>
thank you
Sorry for posting the solution so late.
The problem was found elsewhere. It was actually on the jsp. The select option had a prior radio button selection to it and on its click event i had to show a pre-filled input text box with default value for the same path variable. So when i submitted the form, it binded the value to the input text as comma separated values.
I couldn't find a solution for it through spring path variable. So i used normal html input boxes with different names and binded those values through init binder.

Issue To fetch date format At Edit() In ASP.NET MVC 3

When I edit my one of the form sin ASP.NET MVC 3 in this when I edit a user registration form then I got date in startdate is 21-Mar-12 12:00:00 AM in text box but I need 21-Mar-12.
So how can I format textbox date like that?
You could decorate the DateTime property on your view model with the [DisplayFormat] attribute which allows you to specify a given format:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yy}")]
public DateTime SomeDate { get; set; }
and in your strongly typed view use the EditorFor helper to render the corresponding input field:
#Html.EditorFor(x => x.SomeDate)
As far as binding the value back to a DateTime field when posting back is concerned you could write a custom model binder that will use this format. I have shown an example here.

how to restrict HTML elements while allowing others

How to only allow certain html tags in a text box
Example:
<Strong>
<p>
The code below is where I have been trying to implement the solution in a class created.
[Required]
(Code)
Public string car { get; set; }
How would I go about implementing the solution and is it possible at the point where (code) is written above.
First, you would need to disable the validation for you action with [ValidateInput(false)] attribute but you will need to use that carefully as it will turn off validation for the whole method. You may also disable validation for a particular attribute like :
[Required]
[AllowHtml]
Public string article { get; set; }
ASP.NET MVC3 has built-in attribute to disable validation at property level - so putting [AllowHtml] attribute on properties in model or view model will disable request validation. This is not safe and puts your site at risk. Now it's up to you to ensure that proper data format is provided so you may wan't to give a try a with Regular Expressions to filter out all html code except for the tags you need. You may wan't to take a look at this answer Regex to match all HTML tags except <p> and </p> to get you going.
example from msdn on how to use regex validation with data annotations :
public class Customer
{
[Required]
[RegularExpression(#"^[a-zA-Z''-'\s]{1,40}$",
ErrorMessage="Numbers and special characters are not allowed in the last name.")]
public string LastName { get; set; }
}
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.regularexpressionattribute(v=vs.95).aspx
you may also try the safer way - to implement BBCode like feature. So instead of html tags you use pseudo html tags like [b] instead of < b >
this is easy to accomplish with jQuery :
assuming #text is a field populated with bbcode like text (not visible) and text2 is formatted display - visible :
$(document).ready(function(){
var text = $('#text').html();
text = text.replace("[b]","<b>");
text = text.replace("[/b]","</b>");
$('#text2').html(text);
});
it's not the smartest code but it was a quick one to show you a direction you can take.
The following Regular Expression allows only the Html tags specified:
[RegularExpression(#"^([^<]|<p>|</p>|<strong>|</strong>|a z|A Z|1 9|(.\.))*$")}
This allows for the html <p> </p> <strong> </strong> to be entered while not allowing any other tags.
Add other tags if required.
use AllowHtml attribute and then validate the content using IValidatableObject and Regex,
or write a custom validation attribute to allow only some html tags with Regex, see Phil Haack article http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
[RegularExpression("^[^<>,<|>]+$", ErrorMessage = "Invalid entry.")]
public string FirstName { get; set; }
To avoid mvc error.

MVC 3 - Change Html.TextBox to Html.TextBoxFor

I am using html.textbox for 2 of my datetime field because I need to format them in a specific format but i don't know how to do it by html.textboxfor.
However, I realise i need to have the textboxfor for the validation in my model class to work:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
Any idea how can I change my Html.Textbox below into Html.TextBoxFor with the same setting??
#Html.TextBox("expirydate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" })
#Html.ValidationMessageFor(model => model.ExpiryDate)
Appreciate any help... Thanks...
You don't really need to use TextBoxFor() for validation to work. If your TextBox has the same id as a field in the model, the model binder will pick it up. If you're talking about to get the unobtrusive validation features, you can always manually add the data-* attributes to your TextBox.
However, in this case it sounds like what you really want is a custom editor, using EditorFor(). It's a bit more work, but it will allow you to actually enforce the date/time formatting by giving the user something like a date/time picker control. The basic idea is:
Create a partial view called DateTime.cshtml that is bound to model of type Nullable<DateTime>, and put it into the Shared/EditorTemplates view folder.
Use jQuery and jQueryUI to put an HTML textbox that is styled as a date/time picker into the partial view.
Decorate the property on your model with the [DataType(DataType.DateTime)] attribute
Use Html.EditorFor(model => model.WhateverProperty)
Fortunately, date/time pickers are probably the most popular custom MVC3 editor, so there are plenty of examples to pick from; the code from this question works fine, just make sure to note the suggestion in the answer and replace this line in the partial view:
#inherits System.Web.Mvc.WebViewPage<System.DateTime>
with this:
#model System.DateTime?

MVC3 - 3 decimal places on type double with leading zero

I have a field for weight in Kgs (type double or use something else??).
In edit view I would like the user to enter numbers to the thousandth place.
In display view I would like the Kgs to appear like 560.250
Trying to learn MVC3 + Razor.
Willing to explore JQuery, use of regular expressions, validators, view templates, view models...
The "magic" of MVC based on conventions takes getting used to. Confused as to which approach to use.
Thank you in advance for your help.
You could use data annotations on your view model:
[DisplayFormat(DataFormatString = "{0:#,##0.000#}", ApplyFormatInEditMode = true)]
public double? Weight { get; set; }
and in your view
#Html.EditorFor(x => x.Weight)
will properly format the value in the input field.
Another possibility is to write a custom editor template for the double type (~/Views/Shared/EditorTemplates/double.cshtml):
#model double?
#Html.TextBox("", Model.HasValue ? Model.Value.ToString("#,##0.000#") : "")
and then in your view:
#Html.EditorFor(x => x.Weight)
or if you don't want to override all templates for all double types in your application you could put this into some custom template location like ~/Views/Shared/EditorTemplates/MyFormattedDouble.cshtml and then in your view:
#Html.EditorFor(x => x.Weight, "MyFormattedDouble")
Personally I prefer the first approach which uses data annotations to control the format of the double values.
To format the number just use
#string.Format("{0:0.00}", Model.Weight);
or
#Html.DisplayFor(x => string.Format("{0:0.00}", x.Weight));
#Html.EditorFor(x => string.Format("{0:0.00}", x.Weight));
to Validate
public class Model
{
[Required]
public double Weight{ get; set; }
}
I wouldn't constrain the precision they put in, just make sure that it is a valid number using javascript. You might also constrain input to only include numbers and a period.
If the user puts in something wrong (i.e. not compatible with a double type), MVC will complain when it tries to bind to the model.
its very simple
follow this method
so you have to insert DataFormatString="{0:#,##0.000#Kg}" only on gridview

Resources