I have a PartialView on the index page as follows :-
@{ Html.RenderPartial("ImageUpload"); }
and the PartialView looks like this :-
@model MvcCommons.ViewModels.ImageModel
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FileName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</table>
Now according to the declaration in the top of the PartialView, its supposed to go inside the ViewModels.ImageModel, and inside that class I have a constructor :-
public ImageModel()
{
XDocument imageMetaData = XDocument.Load(uploadsDir + @"/ImagesMetaData.xml");
var images = from image in imageMetaData.Descendants("image")
select new Image(image.Element("filename").Value,
image.Element("description").Value);
this.AddRange(images.ToList<Image>());
}
However, for some reason, in the ImageUpload partial View, when I debug, I am not being redirected to this ViewModel constructor, and as so the model inside the PartialView is null.
Am I missing something here?
How can I get it to actually pass through my constructor? Do I also need to do an @model in the main Index page (where is hosting the PartialView).
Thanks for your help and time
The line @model MvcCommons.ViewModels.ImageModel is used to declare a strongly typed Model, but not instanciate it.
You should use
@{ Html.RenderPartial("ImageUpload", <yourmodel>); }
or more simple :
@Html.Partial("ImageUpload", <yourmodel>)
By the way, in your case:
@Html.Partial("ImageUpload", new ImageModel())
But carefull: your Model should be constructor less and not loading/parsing XML. This should be done in a Controller (and set in the Caching system?).
If you wish to keep your main view Model less, you can also create an Action with the Attribute ChildActionOnly for a partial rendering, and call it with @Html.Action(...): it creates a new ControllerContext.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With