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.
Related
In a MVC 3 Razor Project, I have defined DisplayFormat in ViewModel to format a DateTime Property
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Posted Date")]
public DateTime PostedDate { get; set; }
And I need to make the field Read Only in View
#Html.TextBoxFor(model => model.PostedDate, new { #readonly = "readonly" })
But when displaying the date in TextBoxFor it does not apply the DisplayFormat. If I Change TextBoxFor to a EditorFor DisplayFormat is applied but can not apply the readonly CSS property.
How to apply the date formatting & make the text box readonly?
you can still use editor for when the editor for renders I believe based on your case it should still render to the text-box after it renders you can use a simple jquery function to add an attribute read-only to the rendered text-box
$("#PostedDate").attr("readonly", "readonly");
not sure if it the best solution but you can try it
I have a property of type "float" in my ViewModel. It's being displayed as a TextBox with a default value of "0".
I added an "EditorTemplates" folder inside the "Shared" folder & created a new "Float.cshtml" file with the following content:
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue == 0 ? "" : ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line" })
However, still when I run the application, float fields are still being displayed with a default value of 0.
Thanks
UPDATE
I am just trying to see how ASP.NET reacts to custom templates, till now, the engine is not processing my custom template, something similar to:
LatLng.cshtml
#model float
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line "}) Latitude
On the ViewModel,
[UIHint("LatLng")]
public float? Latitude { get; set; }
On the View,
#Html.EditorFor(model => model.Latitude)
Nothing is changing, default template is being used.
Float is not actually a .NET type, it's a C# type. Float maps to System.Single, so you need to create a Single.cshtml and not a Float.cshtml.
You can also get around this by specifying a UIHint attribute on the model data, or by specifying the template to use in your Editor or EditorFor methods.
An easy workaround is if you just set ViewData.TemplateInfo.FormattedModelValue to return a string in the model, so you don't have to do that weird logic on the view. If you need it to post back a new value (for editing purposes), you just have to add some logic in the controller to turn the string back into a float.
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.
Using the EditorFor templates is a really nice feature of ASP.Net MVC 3, but is it possible to get EditorFor to render an unpopulated template to allow for creation of records?
Or is there some other way to do this?
The ways in which I am trying to do this is as follows:
#Html.EditorFor(model => model)
#Html.EditorFor(x => new List<Business.ViewModel.Affiliate.Contact>())
#Html.EditorFor(new List<Business.ViewModel.Affiliate.Contact>())
#Html.EditorFor(new Business.ViewModel.Affiliate.Contact())
The first one obviously works, however the subsequent ones (which demonstrate what I am trying to do) all fail with the following error:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
The model in question is:
IEnumerable<Business.ViewModel.Affiliate.Contact>
It's the responsibility of the controller to prepare the view model that will be passed to the view. So if you need for example to initialize your view view model with 5 empty contact rows you could do this simply in your controller:
public ActionResult Index()
{
var model = new MyViewModel
{
// Add 5 empty contacts
Contacts = Enumerable.Range(1, 5).Select(x => new Contact()).ToList()
};
return View(model);
}
and in your view use the EditorFor helper as usual:
#model MyViewModel
...
#Html.EditorFor(x => x.Contacts)
This will render the corresponding editor template for each of the 5 elements we have added to the Contacts collection.
If your question doesn't involve AJAX, then I would design the ViewModel as following:
class MyList
{
public List<MyRow> Rows {get;set;}
public MyRow NewRow {get;set;}
}
Then you can easily add a blank editor bound to NewRow property. And in the controller you add the NewRow to Rows on subsequent calls.
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?