Viewbag获取空值

Posted

技术标签:

【中文标题】Viewbag获取空值【英文标题】:Viewbag getting null value 【发布时间】:2020-11-12 08:44:59 【问题描述】:

我有两个控制器 ResultController 和 HomeController。 从结果控制器的索引 ActionResult 我通过 ViewBag 将参数值传递给查看

public IActionResult Index(string listingType, string location, string viewType, [FromQuery] SearchModel searchModel)
        
            SearchQuery model = new SearchQuery(searchModel, location, this.cacheService);
            var locationList = this.searchFactory.GetSearchService(model.ListingType).GetSearchResults(model, listingType);
            ViewBag.listingType = listingType;
            ViewBag.location = location;
            ViewBag.viewType = viewType;
            ViewBag.searchModel = searchModel;
            return View(locationList);
         

Now In View 通过 viewbag 接收值并将值传递给 Homecontroller 的 PropertyDetails

@html.ActionLink(linkText: "Comfortable Apartment in Palace", "PropertyDetails", "Home", new  ListingId = pl.ListingId, listingType= ViewBag.listingType, location= ViewBag.location, viewType= ViewBag.viewType , searchModel= ViewBag.searchModel , null)

在 Homecontroller 的 PropertyDetails 中

public IActionResult PropertyDetails(string listingType, string location, string viewType, [FromQuery] SearchModel searchModel, int ListingId)
        
            SearchQuery model = new SearchQuery(searchModel, location, this.cacheService);
            var locationList = this.searchFactory.GetSearchService(model.ListingType).GetSearchResults(model, listingType);
            var result = locationList.SalesList.FirstOrDefault(s=>s.ListingId==ListingId);
            return View(result);
        

在 PropertyDetails 中,我得到了 viewbag 传递的所有参数值,但 searchmodel 参数为 null。谁能告诉我为什么我在 searchmodel 中得到 null 范围?是否有任何替代方法来传递价值?

搜索模型类

public class SearchModel
    
        public string PI  get; set; 
        public string SIMP  get; set; 
        public string L  get; set; 
        public string S  get; set; 
        public int[] LocationId;
     

【问题讨论】:

【参考方案1】:
@
    var LocationId = (new int[]  1, 2, 3 );

@Html.ActionLink("Comfortable Apartment in Palace", "PropertyDetails", "Home", new  ListingId = 1, listingType = 2, location = 3, viewType = 4, L = "L", PI = "PI", S = "S", SIMP = "SIMP", Locations = string.Join(",", LocationId) , null)

SearchModel 类

public class SearchModel
    
        public string PI  get; set; 
        public string SIMP  get; set; 
        public string L  get; set; 
        public string S  get; set; 
        public int[] LocationId;
        public string Locations  get; set; 
    

正确:

new   L = "L", PI = "PI", S = "S", SIMP = "SIMP" 

错误

 new  searchModel= ViewBag.searchModel 

【讨论】:

这是一个代码唯一的答案,请描述是什么使这个工作和 OP 做错了什么。

以上是关于Viewbag获取空值的主要内容,如果未能解决你的问题,请参考以下文章

获取ViewBag的干净值

在 Jquery 中调用 ViewBag 以从控制器中获取值

如何在ViewBag中传递变量列表

C#/ Asp.NET:在ViewData / ViewBag中设置数据是否有利于每个请求与调用操作方法获取数据?

asp.net mvc 显示 ViewBag 字典到 javascript

如何从 JS 访问 ViewBag