简体   繁体   English

使用 object 或 ViewBag 返回 PartialView

[英]Returning PartialView with object or ViewBag

I'm working on an app where I have an Ajax call to a Controller like so:我正在开发一个应用程序,在该应用程序中,我对 Controller 进行了 Ajax 调用,如下所示:

 $.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和我的 Controller 方法

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.我的 Ajax 调用有效,我将 newList 传递到 _Partial,一切正常。

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:我想要完成的是:我想返回一个 object,而不是只返回 newList 到 Ajax 调用,所以我可能想做类似的事情:

 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在 Ajax Success 我想同时访问ListBooleanTest

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我知道我可以用 JsonResult 做到这一点(返回一个对象),但似乎不能用 PartialView 做到这一点

Is there any way I can return PartialView with Object?有什么办法可以用 Object 返回 PartialView?

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.我会尝试创建一个具有 List 和 Bool 的 ViewModel,并在其中将它们填充到 ActionResult 中并将 ViewModel 传递给 PartialView。 In the PartialView you would have access to the List and Bool.在 PartialView 中,您可以访问 List 和 Bool。

the return i would write like this:我会这样写的回报:

return PartialView(nameof(_Partial), ViewModel);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM