YSOD when passing complex type as razor model in N

2019-07-06 05:26发布

问题:

I'm getting a YSOD when sending a model of type IEnumerable<string> to my Razor view in NancyFX. Everything works well if supply a string as the model, with the relevant @model statement in the view, so its working.

The error is

Unable to discover CLR Type for model by the name of System.Collections.Generic.IEnumerable. Ensure that the model passed to the view is assignable to the model declared in the view.

What have I missed?

View.cshtml

@model System.Collections.Generic.IEnumerable<System.String>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1></h1>
    @foreach (var item in Model)
    {
        <h3>@item</h3>
    }
</body>
</html>

The Module

public class MyModule: NancyModule
{
    public MyModule()
    {
        Get["/"] = parameters => View["View", this.GetModel()];
    }

    private IEnumerable<string> GetModel()
    {
        return new[] { "one", "two" };
    }
}

回答1:

The problem seems to be the @model directive isn't supported in Nancy. Swapping the @model for an @inherits with the correct type fixes the issue:

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<My.ViewModels.WhateverViewModel>


回答2:

In addtion to Greg B's answer, @model is nonetheless a reserved term in the RazorEngine for Nancy, even though this isn't clear from the Nancy Razor View Engine page.

So, you can't declare a variable with the name model and reference it with @model.Property for instance; the view engine will still try to bind it to the model, even if that doesn't actually work (Razor View Engine line 354) and you'll get the same error.



标签: razor nancy