Returning PartialView with object or ViewBag

Viewed 43

I'm working on an app where I have an Ajax call to a Controller like so:

 $.ajax({
            url: '@Url.Action("Test", "Test")',
            async: true,
            type: 'POST',
            dataType: "html",
            data: {
                param1                : paramVal,
            },
            success: function (data) {
                debugger;
                $('#Partial').html(data).show(); //I have a div with this ID to render the PartialView

            }
        });

and my Controller Method

public async Task<ActionResult> Test (string param){

      //doing some processing and returning a List of Datatables

      var newList = new List<DataTable>(); //gets populated with some data

      return PartialView("_Partial",newList); 
}

SO this works perfectly fine. My Ajax call works, I passed the newList into the _Partial, and all good.

What I am trying to accomplish is: Instead of only returning newList to the Ajax call, I'd like to return an object, so I might want to do something like :

 var newList = new List<DataTable>(); //gets populated with some data
 bool test = false;


 return PartialView("_Partial",new {List = newList, BooleanTest = test}); 

and in Ajax Success I'd like to have access to both the List and BooleanTest

success: function (data) {
     debugger;
     alert(data.BooleanTest);
     $('#Partial').html(data.List).show(); //I have a div with this ID to render the PartialView

I know I can do this (return an object) with JsonResult but not seem to be able to do it with PartialView

Is there any way I can return PartialView with Object?

1 Answers

I would try to create a ViewModel which has a List and a Bool and in which you populate them in your ActionResult and pass the ViewModel to the PartialView. In the PartialView you would have access to the List and Bool.

the return i would write like this:

return PartialView(nameof(_Partial), ViewModel);
Related