簡體   English   中英

C#MVC多行文本框有效JSON

[英]C# mvc multiline textbox valid json

我有一個ASP.Net MVC應用程序,該應用程序在頁面上的表單中帶有多行文本框;

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new {@class = "job_create-form", role = "form"}))
{
    @Html.AntiForgeryToken()
    @Html.Label("Notes", new {@class = "form-label"})
    @Html.TextAreaFor(model => model.Notes, new {@class = "form-input", @placeholder = "Please add your notes"})

    <input type="submit" class="button secondary" value="Submit" />
}

由於文本框為多行,因此用戶可以按回車/輸入鍵並在文本框中生成新行-因此,我正努力創建有效的JSON。

當我提交給控制器時,我想生成一個輸出文件。 我一直在針對這個網站驗證我的JSON; https://jsonlint.com/但我似乎不太能到達那里。

這是我的控制器和助手方法;

public ActionResult Index(TestModel model)
{
    string path = @"C:\json.txt";

    if (System.IO.File.Exists(path))
    {
        System.IO.File.Delete(path);
    }

    model.Notes = CleanNotes(model.Notes);

    using (StreamWriter sw = System.IO.File.CreateText(path))
    {
        sw.WriteLine("{");
        sw.WriteLine($"    \"JobName\": \"John Smith\",");
        sw.WriteLine($"    \"Notes\": \"{model.Notes}\",");
        sw.WriteLine($"    \"Title\": \"Sir\"");
        sw.WriteLine("}");
    }

    return View();
}

private string CleanNotes(string notes)
{
    if (notes.Contains("\n"))
    {
        notes = notes.Replace("\n", "\\\n");
    }

     return notes;
}

我不確定如何制作此有效的JSON。 有指針嗎?

根據dbc的建議,我創建了一個匿名對象並將其序列化。

var obj = new
{
    JobName = "John Smith",
    Notes = model.Notes,
    Title = "Sir"
};

JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(obj);

然后將“輸出”變量寫入文件。 謝謝您的幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM