RenderSection is installed as required: false, but still throws "Object reference not installed in object instance"

This code should mark my section as optional.

_layout.cshtml 
@RenderSection("ViewStyles",false)

or

@RenderSection("ViewStyles",required:false)

I tried both.

However, it throws an exception

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

I tried adding an empty section to my views that don't need to use the ViewStyles section

@section ViewStyles {  }

but I still get the same exception.

Is there any other workaround?

+4
source share
2 answers

. , , , , . Object reference not set to an instance of an object - , , null. - , ( , ), null .

, , - :

Foo foo = db.Foos.Find(id);

variable foo Foo, , Foo. Foo Bar. - :

foo.Bar

. , no Foo , Foo null, null Bar, . , : - , , . - :

Foo foo = db.Foos.Find(id);
if (foo != null)
{
    bar = foo.Bar;
}

:

bar = foo != null ? foo.Bar : "Baz";

, Bar foo.Bar, Foo null, "Baz".

+2

@- . , :

@RenderSection ( "", ) " ​​ ". , :

header section

, , :

<body class="@TempData[AppConstants.GlobalClass].ToString() 
         loggedin-@(User.Identity.Name.ToString().ToLower())">

@TempData​​strong > null

+4

All Articles