4
votes

In ASP.NET MVC, I want to reuse a commonly used set of credit card fields by putting them in a partial view, and rendering that partial view inside another form in a parent view.

The issue is that if the CreditCard object is part of a model that is it's self a complex object, when I pass it through to the partial view, on form submission, the field names are missing the parent property name prefix that would allow the default model binder to map the fields to the correct property of the complex object.

Credit card fields rendered in partial view (Incorrect behaviour):

@Html.RenderPartial("~/Views/Pay/CCForm.cshtml", Model.CreditCard ,
 new ViewDataDictionary());

Posts string:

PayOption=1&CreditCardNumberPlainText=0000000000000&StartDateMm=03&StartDateYyyy=2008&ExpiryDateMm=03&ExpiryDateYyyy=2017&SecurityCode=111&IssueNumber=1&X-Requested-With=XMLHttpRequest

Standard form (Correct behaviour) where credit card fields rendered in main view with fields such as:

@Html.TextBoxFor(x => x.CreditCard.IssueNumber, new {@maxlength = 3, @size = 3})

Post string:

PayOption=1&CreditCardInfo.CreditCardNumberPlainText=0000000000000000&CreditCardInfo.StartDateMm=02&CreditCardInfo.StartDateYyyy=2009&CreditCardInfo.ExpiryDateMm=04&CreditCardInfo.ExpiryDateYyyy=2014&CreditCardInfo.SecurityCode=111&CreditCardInfo.IssueNumber=1&X-Requested-With=XMLHttpRequest

1

1 Answers

4
votes

Why don't make a EditorTemplate for this CreditCard class then just use it in your parent view

E.G.

EditorTemplate: CreditCard.cshtml in EditorTemplates folder in the Shared folder add in this file the edit fields for CreditCard. Something like this:

@Html.EditorFor(x => x.IssueNumber)
//........... So on.

then in your view just call:

@Html.EditorFor(x => x.CreditCard)