Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET/Linq-如何在Linq查询中转义HTML字符?_C#_Asp.net_Linq - Fatal编程技术网

C# ASP.NET/Linq-如何在Linq查询中转义HTML字符?

C# ASP.NET/Linq-如何在Linq查询中转义HTML字符?,c#,asp.net,linq,C#,Asp.net,Linq,我有一个Linq查询: from depot in Depots where depot.DepotTypeId == id select new { DepotId = depot.DepotId, GpsLatitude = depot.GpsLatitude, GpsLongitude = depot.GpsLongitude, locationName = depot.DepotName } 这很好,但是locationName可以包含像“and”这样的字符。这很糟糕,因为我需要HTM

我有一个Linq查询:

from depot in Depots
where depot.DepotTypeId == id
select new
{
DepotId = depot.DepotId,
GpsLatitude = depot.GpsLatitude,
GpsLongitude = depot.GpsLongitude,
locationName = depot.DepotName
}
这很好,但是locationName可以包含像“and”这样的字符。这很糟糕,因为我需要HTML5数据属性中的变量。额外的字符会破坏我的HTML语法。因此我尝试了以下方法:

locationName = HttpUtility.HtmlEncode(depot.DepotName)
但这会返回错误:

LINQ to实体无法识别方法“System.String” HtmlEncode(System.String)“”方法,此方法不能为空 翻译成商店表达式


我做错了什么?

这里的主要问题是
HtmlEncode
方法无法转换为SQL,您需要做的是在选择以下选项之前评估LINQ查询(即从数据库中提取数据):

Depots
    .Where(d => d.DepotTypeId == id)
    .AsEnumerable()
    .Select(d => new {
        DepotId = d.DepotId,
        GpsLatitude = d.GpsLatitude,
        GpsLongitude = d.GpsLongitude,
        LocationName = HttpUtility.HtmlEncode(d.DepotName)
    });

您将需要返回数据,然后对其进行编码。您不能将其作为Linq to Entities的一部分来执行。Linq to Entities由于可以转换为SQL的内容而有很多限制。如果我正确理解您的问题,您正在进行格式化(编码)在域对象中或靠近域对象的内容。我认为这不好。与其建议实际答案,不如建议您推迟编码,直到在页面中呈现值。这种方法(显然)的其他好处包括,您可以使用域对象来处理其他内容,而不是提供特定的“视图”“。感谢Oskar和James的反馈,我将使用JavaScript的encodeURIComponent()方法在客户端对其进行编码。