簡體   English   中英

在局部視圖中處理空模型

[英]Handle null model in partial view

這是我的操作,返回用戶的個人資料照片詳細信息

 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>

只是顯式測試null:

@model Namespace.Entity.ProfilePic
if (Model != null)
{
    <label>@Model.UserID</label>
}

然后,只有在有實際實例可以訪問UserId時,它才會嘗試訪問UserId 您還可以利用else塊提供默認的后備。

請確保GetProfilePic(id)返回ProfilePic對象。 我認為_profilePic.GetProfilePic(id )返回非null時,可能無法使用ProfilePic對象實例化模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM