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:
- Escape the
<special character in theConditionsfield of yourFormatObjectlist before returning results - 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 < (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, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } // 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.JsonorNewtonsoft.Jsonto automatically handle<and other special character escaping, and ensure valid JSON. - jQuery: Use
text()for safe, automatic text rendering, or a customescapeHtmlfunction if you need manual control. Don't confuse style code with escaping logic.
内容的提问来源于stack exchange,提问作者zine31

