我有一个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" />
}
文本框是多行的意味着用户可以点击return / enter键并在文本框中生成一个新行 - 我正在努力创建有效的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。 有什么指针吗?
答案 0 :(得分:2)
使用dbc的建议我创建了一个匿名对象并将其序列化;
var obj = new
{
JobName = "John Smith",
Notes = model.Notes,
Title = "Sir"
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(obj);
然后将'output'变量写入文件。 谢谢你的帮助:)