Search code examples
asp.net-mvcvisual-studioif-statementrazorweb-applications

how use if clause code within html in asp.net razor?


I want to write "if clause" in razor for example

 @if (ViewBag.name == null)
   {
   <h3> name is empty.... </h3>
  @}  else {ViewBag.name }

but I get error! would you please help me


Solution

  • @ is used to start writing razor statements i.e. C# code and within html we can still use razor statements starting with @

    The following is the correct syntax for it:

    @if (ViewBag.name == null)
    {
       <h3> name is empty.... </h3>
    }
    else 
    {
        <h3>@ViewBag.name</h3>
    }
    

    it can be more simplified like below:

     <h3> @(ViewBag.name == null ? "name is empty...." : ViewBag.name) </h3>