C# 在局部视图中处理空模型
这是我返回用户个人资料图片细节的操作C# 在局部视图中处理空模型,c#,asp.net-mvc,C#,Asp.net Mvc,这是我返回用户个人资料图片细节的操作 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 PartialV
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
。但是获取异常对象引用未设置为对象的实例。
模型
看法
@model Namespace.Entity.ProfilePic
@Model.UserID
请确保GetProfilePic(id)
返回ProfilePic对象。我认为当\u ProfilePic.GetProfilePic(id
)返回一个非null时,模型可能不会被ProfilePic对象实例化。只需显式测试null:
@model Namespace.Entity.ProfilePic
if (Model != null)
{
<label>@Model.UserID</label>
}
@model Namespace.Entity.ProfilePic
如果(型号!=null)
{
@Model.UserID
}
然后,它只会尝试访问
UserId
,如果有实际的实例访问它。您还可以使用else
块来提供默认回退。您是否在局部视图中定义@model
?是的,作为'@model MyNamespace.Models.ProfilePics'它总是有一个值。有些事情您没有告诉我们。错误是否发生在@Model.UserID
上似乎值得怀疑。您可以发布整个堆栈跟踪吗?什么?这是行不通的,它只会在页面上吐出“Model.UserID”。请忽略,因为我在另一个上下文中回答说,假设模型是在@using中访问的,否则框架会将其视为一个字符串,不带@。
@model Namespace.Entity.ProfilePic
<label>@Model.UserID</label>
@model Namespace.Entity.ProfilePic
if (Model != null)
{
<label>@Model.UserID</label>
}