Checking for null properties on dynamic models in .Net Core

0

I'm trying to pass a dynamic model to a partial view in ASP.NET Core 2.2 (using a partial view to add consistency and maintainability to my code)

Code :

@model dynamic
@{
    var asInput = Model.asInput ?? false;
    var title = Model.title ?? "";
    var dataTooltip = string.IsNullOrWhiteSpace(Model.title) ? "" : "enabled";

    var inputType = "submit";
    if (Model.inputType != null) { inputType = Model.inputType; }

    var cssClasses = "";
    if (string.IsNullOrWhiteSpace(Model.cssClass)) { cssClasses = Model.cssClass; }
}

@if (!asInput)
{
    <h1 class="far fa-eye"></h1>
}
else
{
    <input type="submit" value="&#xf06e;" class="btn btn-block btn- 
   primary @cssClasses" data-tooltip="@dataTooltip" title="@title" />
}

Error :

enter image description here

Error Text (when title is null):

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
  HResult=0x80131500
  Message='<>f__AnonymousType1<bool>' does not contain a definition for 'title'

in the above screenshot, "asInput" and "title" have values, but if they did not they would also produce the same error. As you can see I started with null coalescing but eventually tried a simple "if" which still failed

using "IsNullOrWhiteSpace(Model.Property)" is still an error cause the error is produced when accessing Model.Property

c#
razor
asp.net-core
asked on Stack Overflow Jan 8, 2019 by Ninjanoel • edited Jan 8, 2019 by Ninjanoel

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0