1

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....

aamankhaan
  • 491
  • 1
  • 9
  • 35

1 Answers1

2

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.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • hi it has solved my problem for showing the date format but now....i have binded datepicker with this textbox but it not showing now.... – aamankhaan May 16 '12 at 13:42
  • let me give me in brief so that every one can understand I have used the above to solve the problem of date format it's working fine, but i have attached a datepicker with my Editorfor which is not showing on the editorfor click... <%: Html.EditorFor(m=>m.RenewalDate, new { id = "txtRenewalDate", maxlength = 20, tabindex = 3, @class = "date" })%> below is my editorfor code – aamankhaan May 16 '12 at 13:52