繁体   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