aamankhaan
aamankhaan

Reputation: 491

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

Upvotes: 1

Views: 1254

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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.

Upvotes: 2

Related Questions