I'm trying to load a partial view using JavaScript, in turn the partial view will have a View Bag", to loop through. All is working well, until I try to render the partial view I get an "object Object" error, if I remove the View bag loop the partial view loads
Controller
[HttpPost]
public ActionResult ServiceDetails(int id )
{
int count = 0;
var m = from c in db.ServiceCategoryFields
where c.serviceTypeID == id
select c;
ViewBag.count = count;
ViewBag.m = m.ToList();
return PartialView(m.ToList());
}
Partial View
<table style ="width:100% ">
<tr>
@foreach (var image in (List<String>)ViewBag.m)
{
<td>
@image
</td>
}
</tr>
JS File
type: "POST",
success: function (data) {
display.html('');
display.html(data);
},
error: function (reponse) {
alert("JS Error : " + reponse.toString());
}
Quick Solution
Based on your controller code below
ViewBag.m
would be an instance ofList<ServiceCategoryField>
, but you convert it toList<string>
in the partial viewso you got the error. Assuming that
PropertyName
is the property ofServiceCategoryField
with the value that you want to display inside<td>
tags, you need to convertViewBag.m
toList<ServiceCategoryField>
in the partial view as belowAlternative Solution
The previous solution requires converting
ViewBag.m
and it could produce runtime errors if you convertViewBag.m
to the wrong type. You can avoid the conversion in the partial view by using this alternative solution.The first thing to do is creating a model class that will be used by the partial view, let's say the class name is
ServiceDetailsViewModel
and it hasCount
andImages
propertyCreate an instance of
ServiceDetailsViewModel
, assign the properties, and passmodel
to the partial view in the controller. I assumePropertyName
is a string andc.PropertyName
is where theimage
in the partial view comes fromSet
ServiceDetailsViewModel
as the model by using the below syntax at the top of your partial view codeand loop through
Model.Images
as below