草庐IT

c# - Razor 助手中出现奇怪的 NullReferenceException

coder 2024-05-20 原文

我在 C# Web Forms 应用程序中使用 Razor Helpers。

以下代码在调用时编译并呈现 A-OK:

@helper MemberListItem(string firstname, string lastname, string avatarUrl)
{
    <li>
        @firstname @lastname
        @avatarUrl
    </li>
}

输出(对助手的两次调用):

<li>Bryan Arnold ../../Resources/Images/Placeholders/generic-user-image.jpg</li>
<li>Doug Bland ../../Resources/Images/Placeholders/generic-user-image.jpg</li>

但是当我更改助手时 avatarUrl放在 srcimg 的属性标签,我得到一个 NullReferenceExceptionfirstname .是的,NullReferenceExceptionfirstname .

以下代码编译但在调用时抛出 NRE:

@helper MemberListItem(string firstname, string lastname, string avatarUrl)
{
    <li>
        @firstname @lastname
        <img src="@avatarUrl"/>
    </li>
}

请记住,除了 @avatarUrl 的位置外,我没有改变任何东西。在助手中。

如何让图片显示?

更新 1: 我也试过包装我的 img <text></text> 中的代码(无济于事):

<li>
    @firstname @lastname
    <text>
        <img src="@avatarUrl"/>
    </text>
</li>

更新 2: 这是错误:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

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

Source Error: 

Line 11: {
Line 12:     <li>
Line 13:         @firstname @lastname
Line 14:         <img src="@avatarUrl"/>
Line 15:     </li>

Source File: RazorHelpers\Family.cshtml    Line: 13 

更新 3: 我忘了提到我在一个单独的文件中定义@helper。然后,我从这样的 aspx 模板中调用该助手:

<%= @HelperFile.Helper(parameters).ToString() %>

此外,我认为@Luaan 可能有所作为。我试过摆弄 ~对于我的图像文件的相对路径,认为 Razor 可能会抛出 NRE,因为它无法找到该文件。似乎没有设置 ~在我的项目中工作。

使用静态文件路径:

这个有效:

<img src="/Resources/Images/Placeholders/generic-user-image.jpg"/>

这不是(NullReferenceException):

<img src="~/Resources/Images/Placeholders/generic-user-image.jpg"/>

使用动态文件路径:

这不起作用(NullReferenceException):

<img src="@avatarUrl"/>

这也不行(NullReferenceException):

<img src="~@avatarUrl"/>

注意:Resources目录位于我网站的根目录中。

更新 4:

由于我的项目时间限制,我已经放弃了我原来的助手(这个问题开头提到的那个)并使用了纯 ASPX 模板。但是,我正在尝试使用 Razor 助手来实现此应用程序中的不同功能,但我遇到了与之前描述的相同的问题。

这是一个类似的帮助程序(源代码和编译代码)。助手应该显示一个链接列表,允许用户使用各种身份提供商(google、facebook、twitter、yahoo)注册/登录我的应用程序。这里的故事是一样的;当我只打印 img src 时,助手执行时没有错误,但是当我将 img src 放入实际的 <img/> 时它会抛出 NullReferenceException标签。

来源:

@helper ListGroupGrid(IEnumerable<ExternalIdentityProvider> providers) {
    <div>
        @foreach(var provider in providers){
            @provider.Name
            <img src="@provider.IconUrl"/>
        }
    </div>
}

编译代码(来自 c:\Windows 中的临时 ASP.NET 文件):

#pragma checksum "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "46B0FEE2042706017F4AE53D4EA612F3E73EDF8B"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18052
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ASP.RazorHelpers {
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Helpers;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.WebPages;
    using System.Web.WebPages.Html;

    #line 1 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
    using Aqha.DatabaseHelpers;

    #line default
    #line hidden

    #line 2 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
    using Aqha.RazorExtensions;

    #line default
    #line hidden

    #line 3 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
    using DevExpress.Utils.Drawing.Helpers;

    #line default
    #line hidden


    public class IdentityProvider : System.Web.WebPages.HelperPage {

#line hidden

#line 5 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
public static System.Web.WebPages.HelperResult ListGroupGrid(IEnumerable<IdentityProviderData.ExternalIdentityProvider> providers) {
#line default
#line hidden
return new System.Web.WebPages.HelperResult(__razor_helper_writer => {

#line 5 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"



#line default
#line hidden
BeginContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 202, 11, true);

WriteLiteralTo(__razor_helper_writer, "    <div>\r\n");

EndContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 202, 11, true);


#line 7 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"


#line default
#line hidden

#line 7 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
         foreach(var provider in providers){


#line default
#line hidden
BeginContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 272, 13, false);


#line 8 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
WriteTo(__razor_helper_writer, provider.Name);


#line default
#line hidden
EndContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 272, 13, false);


#line 8 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"



#line default
#line hidden
BeginContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 287, 16, true);

WriteLiteralTo(__razor_helper_writer, "            <img");

EndContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 287, 16, true);

WriteAttributeTo(__razor_helper_writer, "src", Tuple.Create(" src=\"", 303), Tuple.Create("\"", 326)

#line 9 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
, Tuple.Create(Tuple.Create("", 309), Tuple.Create<System.Object, System.Int32>(provider.IconUrl

#line default
#line hidden
, 309), false)
);

BeginContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 327, 4, true);

WriteLiteralTo(__razor_helper_writer, "/>\r\n");

EndContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 327, 4, true);


#line 10 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
        }


#line default
#line hidden
BeginContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 342, 12, true);

WriteLiteralTo(__razor_helper_writer, "    </div>\r\n");

EndContext(__razor_helper_writer, "~/App_Code/RazorHelpers/IdentityProvider.cshtml", 342, 12, true);


#line 12 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"


#line default
#line hidden
});

#line 12 "C:\Users\Public\Documents\VisualStudioProjects\OnlineStable\Aqha\App_Code\RazorHelpers\IdentityProvider.cshtml"
}
#line default
#line hidden


        public IdentityProvider() {
        }

        protected static ASP.global_asax ApplicationInstance {
            get {
                return ((ASP.global_asax)(Context.ApplicationInstance));
            }
        }
    }
}

更新 5: 我做了一些更多的测试。为了尽可能清楚地说明问题,我删除了所有输入参数和额外标记。

考虑以下三个助手:

@helper BaseCase() {
    <img src="/Resources/Images/Placeholders/generic-user-image.jpg"/>
}

@helper VariableBaseCase() {
    var src = "/Resources/Images/Placeholders/generic-user-image.jpg";
    <img src="/Resources/Images/Placeholders/generic-user-image.jpg"/>
    <text>the source is @src</text>
}

@helper Variable() {
    var src = "/Resources/Images/Placeholders/generic-user-image.jpg";
    <img src="@src"/>
    <text>the source is @src</text>
}

当我从 ASPX 调用前两个助手时,它们无一异常(exception)地显示输出(并且图像正常显示):

<%= RazorHelpers.ImageTest.BaseCase().ToString() %>
<%= RazorHelpers.ImageTest.VariableBaseCase().ToString() %>

当我调用最后一个助手时,我得到了我一直得到的同样的错误。

<%= RazorHelpers.ImageTest.Variable().ToString() %>

我希望现在我相信这是一个相对路径问题是正确的。如何让 Razor 显示带有动态 src 的图像我的 Web 窗体应用程序中的属性?

最佳答案

我刚刚遇到了类似的问题 (mvc.net 4)。 我是这样绕过它的:

错误代码:

<input name="ItemUID" type="hidden" value="@ItemUID" />

工作代码:

<input name="ItemUID" type="hidden" @("value=")"@ItemUID" />

关于c# - Razor 助手中出现奇怪的 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935861/

有关c# - Razor 助手中出现奇怪的 NullReferenceException的更多相关文章

  1. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  2. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

  3. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  4. ruby-on-rails - 无法在 Rails 助手中捕获 block 的输出 - 2

    我在使用自定义RailsFormBuilder时遇到了问题,从昨天晚上开始我就发疯了。基本上我想对我的构建器方法之一有一个可选block,以便我可以在我的主要content_tag中显示其他内容。:defform_field(method,&block)content_tag(:div,class:'field')doconcatlabel(method,"Label#{method}")concattext_field(method)capture(&block)ifblock_given?endend当我在我的一个Slim模板中调用该方法时,如下所示:=f.form_field:e

  5. ruby - 使用 rbenv 和 ruby​​-build 构建 ruby​​ 失败,出现 undefined symbol : SSLv2_method - 2

    我正在尝试在配备ARMv7处理器的SynologyDS215j上安装ruby​​2.2.4或2.3.0。我用了optware-ng安装gcc、make、openssl、openssl-dev和zlib。我根据README中的说明安装了rbenv(版本1.0.0-19-g29b4da7)和ruby​​-build插件。.这些是随optware-ng安装的软件包及其版本binutils-2.25.1-1gcc-5.3.0-6gconv-modules-2.21-3glibc-opt-2.21-4libc-dev-2.21-1libgmp-6.0.0a-1libmpc-1.0.2-1libm

  6. ruby-on-rails - 浮点乘法的 Ruby 奇怪问题 - 2

    有没有人用ruby​​解决这个问题:假设我们有:a=8.1999999我们想将它四舍五入为2位小数,即8.20,然后乘以1,000,000得到8,200,000我们是这样做的;(a.round(2)*1000000).to_i但是我们得到的是8199999,为什么?奇怪的是,如果我们乘以1000、100000或10000000而不是1000000,我们会得到正确的结果。有人知道为什么吗?我们正在使用ruby​​1.9.2并尝试使用1.9.3。谢谢! 最佳答案 每当你在计算中得到时髦的数字时使用bigdecimalrequire'bi

  7. ruby - 为什么 return 关键字会导致我的 'if block' 出现问题? - 2

    下面的代码工作正常:person={:a=>:A,:b=>:B,:c=>:C}berson={:a=>:A1,:b=>:B1,:c=>:C1}kerson=person.merge(berson)do|key,oldv,newv|ifkey==:aoldvelsifkey==:bnewvelsekeyendendputskerson.inspect但是如果我在“ifblock”中添加return,我会得到一个错误:person={:a=>:A,:b=>:B,:c=>:C}berson={:a=>:A1,:b=>:B1,:c=>:C1}kerson=person.merge(berson

  8. ruby-on-rails - 从 ActiveAdmin has_many 表单助手中删除 "Add new"按钮 - 2

    我在事件管理员编辑页面中有嵌套资源,但我只想允许管理员编辑现有资源的内容,而不是添加新的嵌套资源。我的代码看起来像这样:formdo|f|f.inputsdof.input:authorf.input:contentf.has_many:commentsdo|comment_form|comment_form.input:contentcomment_form.input:_destroy,as::boolean,required:false,label:'Remove'endendf.actionsend但它在输入下添加了“添加新评论”按钮。我怎样才能禁用它,并只为主窗体保留f.ac

  9. ruby - 安装 tiny_tds 在 mac os 10.10.5 上出现错误 - 2

    我正在使用macos,我想使用ruby​​驱动程序连接到sqlserver。我想使用tiny_tds,但它给出了缺少free_tds的错误,但它已经安装了。怎么能过这个?~brewinstallfreetdsWarning:freetds-0.91.112alreadyinstalled~sudogeminstalltiny_tdsBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtiny_tds:ERROR:Failedtobuildgemnativeextension.完整日志如下:/System

  10. ruby - 如何让几条 haml 线出现在同一行上? - 2

    我有以下haml:9%strongAskedby:10=link_to@user.full_name,user_path(@user)11.small="(#{@question.created_at.strftime("%B%d,%Y")})"这当前将链接和日期放在不同的行上,当它看起来像“链接(日期)”并且日期的类跨度为小...... 最佳答案 您的代码将生成类似这样的html:Askedby:UsernameApril26,2011当您使用类似.small的东西(即使用点而不指定元素类型)时,haml会创建一个implicit

随机推荐