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

ASP.NET MVC文本编码解码功能textarea显示异常求助

Fixing Encoded Text Display & Implementing Decode Functionality in ASP.NET MVC

Alright, let's fix your ASP.NET MVC text encoding/decoding issues step by step. I'll break down why your encoded text isn't showing up in the textarea, then implement the decode functionality properly.

First: Why Isn't Encoded Text Showing in the TextAreaFor?

The core issue here is how ASP.NET MVC's strong-type helpers work. TextAreaFor prioritizes values from ModelState over the actual Model object. When you submit the form, ModelState retains the original (empty) value of EncodedText—so even if you update the Model's EncodedText property, the helper still uses the stale ModelState value.

To fix this, we need to:

  1. Properly update the Model's EncodedText property in your controller.
  2. Clear the stale EncodedText entry from ModelState so the helper uses the Model's new value.

Step 1: Update Your Controller Code

First, make sure your FormData model has the necessary properties (I'll include it for clarity):

public class FormData
{
    public string YourText { get; set; }
    public string EncodedText { get; set; }
    public string DecodedText { get; set; }
    public string SelectedCipher { get; set; }
    public int Key { get; set; }
}

Now revise your controller methods to handle encoding, decoding, and fix the ModelState issue:

private List<string> ciphers = new List<string> { "Caesar" }; // Your cipher list

// Default GET action to load the form
[HttpGet]
public ActionResult Index()
{
    ViewBag.Ciphers = new SelectList(ciphers);
    return View(new FormData());
}

// Handle Encode button submission
[HttpPost]
public ActionResult EncodeText(FormData formData)
{
    ViewBag.Ciphers = new SelectList(ciphers);

    // Implement Caesar cipher encoding logic
    if (!string.IsNullOrEmpty(formData.YourText))
    {
        char[] charArray = formData.YourText.ToCharArray();
        for (int i = 0; i < charArray.Length; i++)
        {
            if (char.IsLetter(charArray[i]))
            {
                char offset = char.IsUpper(charArray[i]) ? 'A' : 'a';
                // Shift letters forward by Key value
                charArray[i] = (char)(((charArray[i] - offset + formData.Key) % 26) + offset);
            }
        }
        formData.EncodedText = new string(charArray);
    }

    // Critical: Clear stale ModelState entry so TextAreaFor uses the Model's new value
    ModelState.Remove("EncodedText");

    return View("Index", formData);
}

// Handle Decode button submission
[HttpPost]
public ActionResult DecodeText(FormData formData)
{
    ViewBag.Ciphers = new SelectList(ciphers);

    // Implement Caesar cipher decoding logic (reverse of encoding)
    if (!string.IsNullOrEmpty(formData.EncodedText))
    {
        char[] charArray = formData.EncodedText.ToCharArray();
        for (int i = 0; i < charArray.Length; i++)
        {
            if (char.IsLetter(charArray[i]))
            {
                char offset = char.IsUpper(charArray[i]) ? 'A' : 'a';
                // Shift letters backward by Key value (handle negative shifts)
                int shifted = charArray[i] - offset - formData.Key;
                shifted = shifted < 0 ? shifted + 26 : shifted;
                charArray[i] = (char)((shifted % 26) + offset);
            }
        }
        formData.DecodedText = new string(charArray);
    }

    // Clear stale ModelState entry for DecodedText
    ModelState.Remove("DecodedText");

    return View("Index", formData);
}

Step 2: Simplify & Fix Your View

You don't need separate views for Encode/Decode—we'll use a single Index view with strong-type helpers for better model binding:

@model StringCoder_ASP.NET_MVC.Models.FormData

<div style="padding: 20px;">
    @using (Html.BeginForm())
    {
        <div class="form-group">
            @Html.LabelFor(m => m.YourText, "Input your text:", new { @class = "control-label" })
            <br />
            @Html.TextAreaFor(m => m.YourText, new { @class = "form-control", rows = 3 })
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.EncodedText, "Your encoded text:", new { @class = "control-label" })
            <br />
            @Html.TextAreaFor(m => m.EncodedText, new { @class = "form-control", rows = 3 })
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.DecodedText, "Your decoded text:", new { @class = "control-label" })
            <br />
            @Html.TextAreaFor(m => m.DecodedText, new { @class = "form-control", rows = 3 })
        </div>

        <div class="form-group">
            <input type="submit" value="Encode" formaction="@Url.Action("EncodeText")" class="btn btn-primary" />
            <input type="submit" value="Decode" formaction="@Url.Action("DecodeText")" class="btn btn-secondary" style="margin-left: 10px;" />
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.SelectedCipher, "Select a cipher:", new { @class = "control-label" })
            @Html.DropDownListFor(m => m.SelectedCipher, ViewBag.Ciphers as SelectList, new { @class = "form-control" })
        </div>

        <div class="form-group">
            @Html.LabelFor(m => m.Key, "Enter a key:", new { @class = "control-label" })
            @Html.TextBoxFor(m => m.Key, new { @class = "form-control", type = "number" })
        </div>
    }
</div>

Key Improvements Explained

  • ModelState Clearing: Calling ModelState.Remove("EncodedText") and ModelState.Remove("DecodedText") ensures the strong-type helpers use the updated Model values instead of stale form data.
  • Single View: Using one view reduces code duplication and keeps the user experience consistent.
  • Strong-Type Helpers: LabelFor, TextAreaFor, and DropDownListFor improve model binding accuracy and make your code more maintainable.
  • Proper Decode Logic: The DecodeText action reads from EncodedText, decodes it, and populates DecodedText—exactly matching your requirement.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:20:44