如何从MVC ViewComponents返回JsonResult?

时间:2019-01-15 09:38:38

标签: model-view-controller jsonresult view-components

我在下面创建了一个具有搜索逻辑的ViewComponent,并将搜索结果用于更新页面上的2个不同视图。为此,我创建了一个“ SearchResultsViewModel”,然后更新了Section1和Section2。在客户端,我有AJAX根据返回的内容更新视图。如何从ViewCompoment发送JSON结果?有可能吗?

public class SearchResultsViewModel
    {
        public string Section1 { get; set; }
        public string Section2 { get; set; }
    }

public async Task<IViewComponentResult> MyViewComponent(SearchModel model, string user)
{
    var results = new SearchResultsViewModel();
    ............

    results.Section1 = renderer.ViewToString("../Shared/Components/Search/_Section1", model);
            resultsViewModel.SearchResults= _renderer.ViewToString("../Shared/Components/SuperSearch/_Section2", model);

return new ContentViewComponentResult(JsonConvert.SerializeObject(results));

}

0 个答案:

没有答案