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.mwould be an instance ofList<ServiceCategoryField>, but you convert it toList<string>in the partial viewso you got the error. Assuming that
PropertyNameis the property ofServiceCategoryFieldwith the value that you want to display inside<td>tags, you need to convertViewBag.mtoList<ServiceCategoryField>in the partial view as belowAlternative Solution
The previous solution requires converting
ViewBag.mand it could produce runtime errors if you convertViewBag.mto 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
ServiceDetailsViewModeland it hasCountandImagespropertyCreate an instance of
ServiceDetailsViewModel, assign the properties, and passmodelto the partial view in the controller. I assumePropertyNameis a string andc.PropertyNameis where theimagein the partial view comes fromSet
ServiceDetailsViewModelas the model by using the below syntax at the top of your partial view codeand loop through
Model.Imagesas below