MVC 3 - Change Html.TextBox to Html.TextBoxFor - asp.net-mvc-3

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?

Related

mvc3 is there a way to change the naming system of razor

I have a partial view that allows Html and the rendered name attribute of the <textarea> is throwing everything off, for instance this is my text area
#Html.TextAreaFor(model => model.cars.mycars)
causes the attribute to render as name="cars.mycars", is there anyway to change that to cars_mycars without using #Name ?
The reason why I want cars_mycars is because it is a field that has AllowHtml in it in the model
[AllowHtml]
public string mycars { get; set; }
In order for AllowHtml to work I would need a strongly typed model such as #Html.TextAreaFor(model => model.mycars) but I am using multiple models in 1 view therefore I have
#Html.TextAreaFor(model => model.cars.mycars, #new{id="cars_mycars",#Name="cars_mycars"})
This is all in a partialview and when I try to submit it nothing happens at all. That is the only field in the form so the issue much lie there and in addition if I put
ValidateInput(False)
on the action method then everything works fine which leads me back to the #name convention not working .
You can try like this
#Html.TextArea("cars_mycars")

how to bind model property to html helper textboxfor in mvc3

i want to tightly bind my property using html helper for TextBoxFor but i am not able to do so,i have simply binded using Textbox but i want to get data assign to textbox on httpPost
below is how i have done using simple HtmlHelper textbox
<%: Html.TextBox("RenewalDate", (string.Format("{0:yyyy/MM/dd}", Model.RenewalDate)), new { id = "txtRenewalDate", maxlength = 20, tabindex = 3, #class = "date" })%>
i dont want to use FormCollection that's why i want to bind tightly with TextBoxFor so that on httpPost my model has the value assigned to the Model.RenewalDate
please help....
Use an editor template, it's much easier:
<%= Html.EditorFor(x => x.RenewalDate) %>
and you could decorate your view model property with the DisplayFormat attribute to specify the desired format:
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime RenewalDate { get; set; }
and then your POST controller action will take the view model as action parameter.
[HttpPost]
public ActionResult SomeAction(MyViewModel model)
{
...
}
And in order to apply the HTML attributes such as class, tabindex and maxlength to this editor template you could write a custom metadata provider as shown in the following article.
Also since the date is using the yyyy/MM/dd it is possible that the default model binder is not able to parse the value back because the default model binder uses the current culture settings. To resolve this issue you could write a custom model binder as I showed in this thread.

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.

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

ASP.Net MVC 3 EditorTemplate for DateTime Fields Error

This code was converted from some ASP.Net MVC 2 code in this tutorial:
MVC 2 Editor Template with DateTime
It is a custom EditorTemplate for DateTime fields stored as 'EditorTemplates/DateTime.cshtml'.
#Model DateTime?
#Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { #class = "datePicker" })
However I get the following error when using #Html.EditorFor(model => model.NewAbsence.StartDate):
CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
I've seen some similar posts on here which mention casting the parameter of the EditorFor method, however I cannot seem to get this to work in my example.
Could someone please point out what I will need to change in my code. Thanks.
Actually it's #model with lowercase m:
#model DateTime?
^
instead of:
#Model DateTime?
So to sort of summarize what people are saying, and make it a bit more generic. If your view is declaring that it accepts dynamic models:
#model dynamic
Then things like extension methods will not be able to infer the types of arguments passed to them. Here are two examples (using Razor because it's awesome):
#Html.TextBox("myTextBoxName", Model.MyTextBoxValue)
#Html.DropDownList("myDropDownName", Model.MySelectList))
In these cases, the engine doesn't know what types Model.MyTextBoxValue or Model.MySelectList are, therefore it can't figure out what overloads of the extension methods to compile. So you just help it along with some strong typing:
#Html.TextBox("myTextBoxName", (string)Model.MyTextBoxValue)
#Html.DropDownList("myDropDownName", (SelectList)Model.MySelectList))
By the way, just to stop people from potentially pulling out their hair, that SelectList has to be properly instantiated with something like:
var items = List<SelectListItem>();
...
new SelectList(items, "Value", "Text");
As a temporary work around I am using:
<div class="editor-field date-field">
#Html.EditorFor(model => model.NewAbsence.StartDate)
#Html.ValidationMessageFor(model => model.NewAbsence.StartDate)
</div>
Then using the jQuery selector:
$(".date-field > input").datepicker({
showOn: "button",
buttonImage: "*pathtoimage*"
});
To apply the date picker to the input tags within the 'date-field' div. However this still doesn't format the date value how I want it to display initially, and cuts out the editor template entirely.
The error message comes from your textbox statement. In a template, this becomes a dynamic expression, and .Net doesn't know how to type the Model properties.
#Html.TextBox("", (string)(Model==null ? Model.Value.ToShortDateString() : string.Empty), new { style = "width: 10em;", #class="datefield" })
Explicitly cast your date value as string, and the dynamic expression has the information it needs. I also had a problem with the .HasValue property, but that wasn't the point of your question.

Resources