Reputation: 1533
What would be the best way to for a razor view to handle multiple models? for an MVC3 application.
I have two models, both similar, but the Postcode field is required for one model and not for another
public class IrelandPostcodeLookupViewModel , IWithProgress
{
readonly Progress _Progress = new Progress(Step.Delivery);
public Progress Progress
{
get { return _Progress; }
}
[Required(ErrorMessage = "Please enter your house number or name")]
[DisplayName("House number or name")]
public string HouseNumber { get; set; }
[StringLengthWithGenericMessage(50)]
[DisplayName("Eircode")]
public string Postcode { get; set; }
}
public class PostcodeLookupViewModel , IWithProgress
{
readonly Progress _Progress = new Progress(Step.Delivery);
public Progress Progress
{
get { return _Progress; }
}
[Required(ErrorMessage = "Please enter your house number or name")]
[DisplayName("House number or name")]
public string HouseNumber { get; set; }
[StringLengthWithGenericMessage(50)]
[Required(ErrorMessage = "Please enter your postcode")]
[DisplayName("PostCode")]
public string Postcode { get; set; }
}
In the controller I want to use a particular view model depending on a country I am passed. Something like
public virtual ActionResult PostcodeLookup(string country)
{
if (country == Country.UnitedKingdom)
return View(new PostcodeLookupViewModel());
else
return View(new IrelandPostcodeLookupViewModel());
}
I was handling this in the view with
@model dynamic
The problem I have with this is my view contains partial views
@Html.Partial("~/Views/Shared/_Progress.cshtml", Model.Progress)
and I run into the error 'HtmlHelper' has no applicable method named 'Partial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched'
Can anyone advise how I can handle the Partial View?
Thanks
Upvotes: 1
Views: 300
Reputation: 24280
Because Model
is dynamic
, also Model.Progress
produces a dynamic
.
This is true for all properties and function calls on a dynamic
object, no matter how deep you'd go.
To solve this you can typecast the Model.Progress
object:
@Html.Partial("~/Views/Shared/_Progress.cshtml", (Progress)Model.Progress)
Upvotes: 1