我試圖在if else我的模型中使用一個包含unameasusername但如果它null會Login/Register出現的陳述句。打賭,如果它!= null會ViewBag.username顯示。
<li class="nav-item">
@if (Model.uname != null)
{
<a class="nav-link changing-color">@ViewBag.username</a>
}
else
{
<a class="nav-link changing-color" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight" id="login-register">Login / Register</a>
}
</li>
我試圖這樣做,但它總是拋出一個錯誤
Object reference not set to an instance of an object.
反正周圍有做這種if else嗎?
編輯:
此外,這些只是我在我的.cs
public IActionResult Index()
{
return View();
}
當我輸入[HttpGet]or[HttpPost]時,它會顯示與上面相同的錯誤。
編輯:
我還嘗試使用<運算子作為boolean但標記為紅旗。
編輯:
我也忘了添加我的HomeModel:
public class HomeModel
{
public string uname { get; set; }
public string password { get; set; }
public string email { get; set; }
public string user_type { get; set; }
}
uj5u.com熱心網友回復:
你需要稍微改變你的代碼。您檢查用戶名 null 但不是模型本身,因此您需要先檢查。
<li class="nav-item">
@if (Model?.uname != null)
{
<a class="nav-link changing-color">@ViewBag.username</a>
}
else
{
<a class="nav-link changing-color" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight" id="login-register">Login / Register</a>
}
</li>
此外,如果您看到您的 Index ActionMethod。你沒有在那里傳遞任何模型。所以例外是 Model null 而不是 Model.uname。
uj5u.com熱心網友回復:
您的代碼中的第一個問題是您沒有ViewBag在控制器中設定任何內容,ViewBag它是一個動態物件,用于將資料從控制器傳遞到視圖,因此您需要先設定它。
你代碼中的第二個問題是你只是return View()在你的控制器中,你沒有傳遞任何模型來查看,所以當你想對模型的屬性進行一些判斷時,專案會報告NullReferenceException.
參考這個演示:
public IActionResult Index()
{
HomeModel model = new HomeModel()
{
//Set the value of the property according to your situation
}
ViewBag.username= model.uname;
return View(model);
}
看法
<li class="nav-item">
@if (Model.uname != null)
{
<a class="nav-link changing-color">@ViewBag.username</a>
}
else
{
<a class="nav-link changing-color" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight" id="login-register">Login / Register</a>
}
</li>
在我看來,如果模型具有價值,你可以只使用@model.uname而不是@ViewBag.username
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497171.html
上一篇:ASP.NETCore在關機/致命錯誤之前如何做一些事情?
下一篇:如何在EFCoreOnModelCreating(ModelBuildermodelBuilder)中生成錯誤訊息
