You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#与jQuery中特殊字符转义方法及<字符转义失效问题求助

Hey there! Let's break down and fix your issues step by step, since I see you're dealing with escaping the < character in your FormatObject data and having trouble with your existing C#/jQuery code not working as expected.

Core Requirements Recap

You have two key goals:

  1. Escape the < special character in the Conditions field of your FormatObject list before returning results
  2. Fix the non-functional escape logic in your C# and jQuery code

C# Side: Fixing Escape Logic

First, let's address your C# code—your current approach to building strings manually is the root cause of unescaped characters, plus it's error-prone for JSON formatting.

1. Ditch Manual String Concatenation for Proper JSON Serialization

Your FormatObject.ToString() method manually builds a JSON-like string, which doesn't handle character escaping at all. Instead, use .NET's built-in JSON serializers (either System.Text.Json for modern .NET or Newtonsoft.Json for broader compatibility) to automatically handle escaping.

Here's the revised FormatObject class:

// For .NET Core 3.0+ (use System.Text.Json)
using System.Text.Json;

// OR for .NET Framework/older projects (use Newtonsoft.Json)
// using Newtonsoft.Json;

public class FormatObject { 
    public int Id { get; set; } 
    public int IdObject { get; set; } 
    public string Conditions { get; set; } 
    public List<int> SelectedAttributesId { get; set; } 

    // Optional: Custom method to get a properly escaped JSON string
    public string ToEscapedJson() {
        // System.Text.Json approach (automatically escapes <, >, &, etc.)
        return JsonSerializer.Serialize(this);
        
        // Newtonsoft.Json approach (configure to escape HTML characters)
        // return JsonConvert.SerializeObject(this, new JsonSerializerSettings {
        //     StringEscapeHandling = StringEscapeHandling.EscapeHtml
        // });
    }
}

This way, any < in the Conditions field will be automatically escaped to \u003C (System.Text.Json) or &lt; (Newtonsoft.Json), ensuring valid JSON and safe rendering.

2. Fix the GetJsonForQuery Method

Your JsonResult should rely on .NET's built-in serialization instead of manual handling. Here's how to ensure escaping works here too:

public JsonResult GetJsonForQuery(ObjectJson serializedJson) { 
    if (serializedJson.MainObjects == null) { 
        // Configure serialization options to enforce HTML character escaping
        var jsonOptions = new JsonSerializerOptions
        {
            // Default encoder already escapes <, >, &—no extra config needed here
            // For explicit control, use: Encoder = JavaScriptEncoder.Default
        };

        var errorResponse = new { 
            updated = DateTime.UtcNow.ToString("o"), 
            errorNoItemSelected = true 
        };

        JsonResult result = Json(errorResponse, jsonOptions, JsonRequestBehavior.AllowGet); 
        result.MaxJsonLength = Int32.MaxValue; 
        System.Diagnostics.Debug.WriteLine(serializedJson.MainObjects); 
        return result; 
    }

    // For non-null MainObjects, serialize directly (escaping happens automatically)
    var successResponse = new { 
        updated = DateTime.UtcNow.ToString("o"),
        formatObjects = serializedJson.MainObjects
    };

    return Json(successResponse, new JsonSerializerOptions(), JsonRequestBehavior.AllowGet);
}

If you're using Newtonsoft.Json in an older ASP.NET project, add this configuration to your Global.asax or Startup.cs to ensure global escaping:

// .NET Framework example
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new Newtonsoft.Json.JsonSerializerSettings
{
    StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml
};

Why Your Original C# Code Failed

Your manual ToString() method simply injected the raw Conditions value into the string without any escaping. This not only leaves < unhandled but also risks invalid JSON if Conditions contains quotes or other special characters. Always use proper serialization libraries!


jQuery Side: Fixing Escape Logic

First, a critical correction: your line obj.$el.find('input:not(:checkbox)').addClass('input-sm'); has nothing to do with escaping special characters—it's just adding a CSS class to non-checkbox inputs. That's why it had no effect on your escape needs.

1. Safe Text Rendering (Automatic Escaping)

If you're displaying the Conditions text in the DOM, use jQuery's text() method instead of html(). text() automatically escapes HTML characters like <, so they're displayed as plain text instead of being parsed as HTML:

// Example: Assume you've fetched data from your C# endpoint
var formatObject = /* your fetched data */;
// Display Conditions safely
obj.$el.find('.conditions-output').text(formatObject.Conditions);

2. Manual HTML Escaping (If Needed)

If you need to process the string before rendering, use a helper function to escape HTML special characters explicitly:

function escapeHtml(str) {
    return str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

// Usage example
var escapedConditions = escapeHtml(formatObject.Conditions);
// Now you can safely use html() if needed
obj.$el.find('.conditions-output').html(escapedConditions);

Why Your Original jQuery Code Failed

You confused CSS class manipulation with character escaping—those are completely separate operations. The line you thought was for escaping was only styling inputs, so it never touched your special characters.


Final Recap

  • C#: Stop manually building JSON strings. Use System.Text.Json or Newtonsoft.Json to automatically handle < and other special character escaping, and ensure valid JSON.
  • jQuery: Use text() for safe, automatic text rendering, or a custom escapeHtml function if you need manual control. Don't confuse style code with escaping logic.

内容的提问来源于stack exchange,提问作者zine31

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:52:28