这是我的动作,返回用户的个人资料照片
public ActionResult Avatar(int id)
{
// var userid = int.Parse(User.Identity.Name);
var model = _profilePic.GetProfilePic(id);
if (model == null)
model = new ProfilePic {UserID = id};
return PartialView(model);
}
在视图中我想访问@Model.UserID
。但是获得例外Object reference not set to an instance of an object.
模型
public class ProfilePic
{
public int UserID { get; set; }
public string ProfilePicID { get; set; }
public string MimeType { get; set; }
public string Photo { get; set; }
public string PhotoThumb { get; set; }
}
查看
@model Namespace.Entity.ProfilePic
<label>@Model.UserID</label>
答案 0 :(得分:0)
只需显式测试null:
@model Namespace.Entity.ProfilePic
if (Model != null)
{
<label>@Model.UserID</label>
}
然后,如果有一个实际的实例来访问它,它将只尝试访问UserId
。您还可以使用else
块来提供默认回退。
答案 1 :(得分:-1)
请确保GetProfilePic(id)
返回ProfilePic对象。我认为当_profilePic.GetProfilePic(id
)返回非null时,模型可能无法使用ProfilePic对象进行实例化。