There is no implicit conversion between 'PartialViewResu

本文关键字:PartialViewResu between conversion is no implicit There | 更新日期: 2023-09-27 18:10:41

使用条件运算符时出现错误:

public ActionResult Topic()
{
   var model = new TopicMasterViewModel();
   // do something...
   return model.Topic != null && model.Topic.Count > 0 ? PartialView("../Home/_Topic", model) : Json(new { });
}

错误提示:

条件表达式的类型无法确定,因为'System.Web.Mvc '之间没有隐式转换。PartialViewResult'和'System.Web.Mvc.JsonResult'

为什么?ActionResult可以同时返回PartialView()Json()

There is no implicit conversion between 'PartialViewResu

类型PartialViewResultJsonResult不是隐式可转换的,因此,在三元操作符中,两种情况的返回类型应该匹配,而在这种情况下不是。

你必须在这里使用正常的if else,如:

if(model.Topic != null && model.Topic.Count > 0)
    return PartialView("../Home/_Topic", model) 
else
    return Json(new { });

对于三元操作符: 条件操作符的表达式具有特定的类型。表达式中使用的两种类型必须是相同类型或彼此隐式可转换。

而在您的情况下,'System.Web.Mvc.PartialViewResult''System.Web.Mvc.JsonResult'不是隐式可转换的。

您可以使用正常的if条件。