C# 在';PartialViewResult';和';JsonResult';
使用条件运算符时出现错误:C# 在';PartialViewResult';和';JsonResult';,c#,asp.net-mvc-5,C#,Asp.net Mvc 5,使用条件运算符时出现错误: public ActionResult Topic() { var model = new TopicMasterViewModel(); // do something... return model.Topic != null && model.Topic.Count > 0 ? PartialView("../Home/_Topic", model) : Json(new { }); } 错误是这样的: 无法确定条件表达
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()
类型PartialViewResult
和JsonResult
不是隐式可转换的/casable,因此,在三元运算符中,两种情况下的返回类型都应该匹配,而在这种情况下则不匹配
如果这里有以下情况,则必须使用普通:
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
条件