This project is read-only.
1

Closed

Null string exception at transformtext() when using RazorGenerator with generator as template

description

I am using RazorGenerator with generator as template for console application. My cshtml file looks like below:
Model has DocumentRefNumber property which is string. Now if DocumentRefNumber is null then it throws exception when trying to do TransformText. I know one solution is to use nullsafe guard like @Model.DocumentRefNumber != null ? @Model.DocumentRefNumber : string.Empty. But I don't want to do this way as I don't like to write this nullsafe guard condition in cshtml file for every string property in Model.

CsHtml file:

@* Generator : Template *@
@functions {
public PrintHeaderDto Model { get; set; }
}
@using Harmony.Dto.Print

<!DOCTYPE html >

<html >
<head id="Head1" runat="server">
    <title></title>
 </head>
<body >
    <div id="printHeader">
       <h2>@Model.DocumentRefNumber</h2>
    </div>
</body>
</html>
Closed Aug 4, 2011 at 7:55 PM by davidebbo
Pranav made to change to allow @foo where foo is null. But the fact that @foo.bar blows up when foo is null is not really something we can fix.

comments

davidebbo wrote Aug 3, 2011 at 6:32 PM

You should view this the same way as if you were writing a method that takes Model as a parameter and then tried to use it everywhere. There is really no magic in what the template does. It's just your code that ends up running exactly as you write it (see the generated code under the .cshtml file). You can either safe guard the calls, or as an alternative you can expose distinct properties for each thing you want to render, instead of using a single Model object.

pranavkm wrote Aug 4, 2011 at 5:49 PM

The Write method in WebPages does not throw (simply no-ops) when we pass it a null value whereas T4 seems to throw. I'll fix it so we're closer to the behavior elsewhere.

davidebbo wrote Aug 4, 2011 at 6:38 PM

Yes, but when calling Model.SomeProp, there just isn't much we can do to automatically protect against Model being null.

pranavkm wrote Aug 4, 2011 at 6:48 PM

Oh sure, we wouldn't do something magical to make this work - but if the value to be written is null, we could certainly not throw.

pranavkm wrote Aug 4, 2011 at 6:49 PM

Fixed in changeset b98f3243b5cb

bhavini wrote Aug 5, 2011 at 9:45 AM

Thanks.. It fixed my problem.