Home > Software design >  How can I use if else Model with value as null?
How can I use if else Model with value as null?

Time:06-25

I was trying to use an if else statement with my model that contains uname as username but if its null then Login/Register will show up. Bet if its != null the ViewBag.username will show.

<li >
    @if (Model.uname != null)
    {
        <a >@ViewBag.username</a>
    }
    else
    {
        <a  data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight" id="login-register">Login / Register</a>
    }
</li>

I tried to do this but it always throw an error

Object reference not set to an instance of an object.

Is there anyway around to do this kind if else?

EDIT:

In addition these is only what I'm using on my .cs

public IActionResult Index()
{
    return View();
}

When I put an [HttpGet] or [HttpPost] it shows the same error above.

EDIT:

I also tried by using < operator as boolean but tag as redflag.

EDIT:

I also forgot to add my 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; }
}

CodePudding user response:

You need to change your code a little. You check the user name null but not the model itself so you need to check that first.

 <li >
     @if (Model?.uname != null)
     {
         <a >@ViewBag.username</a>
     }
     else
     {
         <a  data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight" id="login-register">Login / Register</a>
     }
 </li>

Also if you see your Index ActionMethod. You do not pass any model there. So the exception is at Model null not Model.uname.

CodePudding user response:

The first question in your code is you don't set any ViewBag in your controller, ViewBag is a dynamic object to pass data from controller to view, So you need to set it first.

The second question in your code is you just return View() in your controller, you don't pass any model to view, So when you want to make some judgments on the propertis of the model, the project will report NullReferenceException.

Refer to this demo:

public IActionResult Index()
    {
         HomeModel model = new HomeModel()
         {
             
            //Set the value of the property according to your situation
         }

         ViewBag.username= model.uname;
        return View(model);
    }

View

<li >
     @if (Model.uname != null)
     {
         <a >@ViewBag.username</a>
     }
     else
     {
         <a  data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight" id="login-register">Login / Register</a>
     }
 </li>

In my opinion, If the model has the value, you can just to use @model.uname instead of @ViewBag.username

  • Related