具有键“Shape”的 ViewData 项属于类型“System.String”,但它必须属于类型“IEnumerable<SelectListItem>”。
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。异常详细信息: System.InvalidOperationException: 具有键“Shape”的 ViewData 项属于类型“System.String”,但它必须属于类型“IEnumerable<SelectListItem>”。
源错误:
行 107: <span class="label UserEditlabel">体型:</span>
行 108: <div class="fl">
行 109: <%= Html.DropDownList("Shape")%>
行 110:
行 111: </div>
|
出错原因: 忘了设置ViewData["shape"]为SelectList类型,SelectList实现了 "IEnumerable<SelectListItem>"接口
[Serializable]
public class ProfileInformation
{
public static SelectList GetShapeList(String shape)
{
List<SelectListItem> shapeList = new List<SelectListItem>()
{
new SelectListItem() { Value = "F", Text = "偏胖" },
new SelectListItem() { Value = "N", Text = "正常" },
new SelectListItem() { Value = "T", Text = "偏瘦" }
};
return new SelectList(shapeList, "Value", "Text", shape);
}
}
[Authorize]
public ActionResult UserProfile()
{
string id = HttpContext.User.Identity.Name.ToString();
ProfileBase profileBase;
if (!String.IsNullOrEmpty(id))
{
profileBase = ProfileBase.Create(id);
}
else
{
profileBase = HttpContext.Profile as ProfileBase;
}
ProfileInformation profile =( ProfileInformation) profileBase.GetPropertyValue("ProfileInformation") ;
ViewData["shape"] = ProfileInformation.GetShapeList(profile.Shape); //此处设置ViewData["shape"]为SelectList类型即可
}