2

My issue is similar to:

Compound View Model object causing remote validation failure

My models:

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    [Remote("CheckZip", "Validation")]
    public string PostalCode { get; set; }
    public string Country { get; set; }
}

public class OrderViewModel
{
    public Address ShippingAddress { get; set; }
    public Address BillingAddress { get; set; }
    public string OrderItem { get; set; }
    public string OrderQuantity { get; set; }
}

The rendered HTML creates the fields ShippingAddress_Postalcode and BillingAddess_PostalCode.

The CheckZip action:

public ActionResult CheckZip (string PostalCode)
{
    ...
}

which of course doesn't work because PostalCode isn't being sent instead its either ShippingAddress_Postalcode or BillingAddess_PostalCode. How can I use the same CheckZip action to handle the same sub-property that exists in multiple properties?

Community
  • 1
  • 1
Shawn Doe
  • 21
  • 2

2 Answers2

1

Can you try as follows: In the controller, add two methods,

[ActionName("CheckZip")]
public ActionResult CheckZip (Address ShippingAddress)
{
    ...
}

[ActionName("CheckZip")]
public ActionResult CheckZip1 (Address BillingAddress)
{
    ...
}
1

CheckZip should take an Address rather than a string and then check the zip code property of that address.

public ActionResult CheckZip (Address addressToCheck){    ...}
Joe Cartano
  • 2,997
  • 3
  • 22
  • 40
  • How would I mark up the HTML to make CheckZip take an Address? Or would the work be done on the controller using a bind attribute? My view now looks like: <%= Html.TextBoxFor(model => model.ShippingAddress.PostalCode)%> – Shawn Doe Apr 21 '11 at 20:07
  • The work should be done in the controller. You can avoid using the bind attribute if you name your parameter properly. I would look at the query string coming back when remote validation fires, this gives you a good clue as to how you should structure your method so that it will bind properly. – Joe Cartano Apr 21 '11 at 21:58
  • It seems like having CheckZip take an address would produce the same problem in that the query string would still be sending different names (either ShippingAddress or BillingAddress) to CheckZip. The Bind attribute has a Prefix parameter that adds a prefix to the query string name. I need some way of removing a prefix in order to reuse the CheckZip action. – Shawn Doe Apr 22 '11 at 13:54
  • This is complicated by the fact that I can't set the Name attribute using an HtmlHelper since it seems to be the name that is being sent to the action. – Shawn Doe Apr 22 '11 at 15:06
  • The simplest solution is probably to have to wrapper methods you call that end up calling a method that actually does the validation work. You could name the parameters in each wrapper method to match ShippingAddress and BillingAddress. – Joe Cartano Apr 22 '11 at 16:43