[英]C# mvc multiline textbox valid json
I have an ASP.Net MVC application with a multiline textbox in a form on a page; 我有一个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" />
}
With the textbox being multiline means the user can hit the return/enter key and generate a new line within the text box - I'm struggling to create valid JSON as a consequence of that. 由于文本框为多行,因此用户可以按回车/输入键并在文本框中生成新行-因此,我正努力创建有效的JSON。
When I submit to the controller I want to generate an output file. 当我提交给控制器时,我想生成一个输出文件。 I have been validating my JSON against this site; 我一直在针对这个网站验证我的JSON; https://jsonlint.com/ But I can't seem to quite get there. https://jsonlint.com/但我似乎不太能到达那里。
Here is my controller and helper method; 这是我的控制器和助手方法;
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;
}
I'm not sure how to make this valid JSON. 我不确定如何制作此有效的JSON。 Any pointers? 有指针吗?
Using dbc's advice I created an anonymous object and serialized it; 根据dbc的建议,我创建了一个匿名对象并将其序列化。
var obj = new
{
JobName = "John Smith",
Notes = model.Notes,
Title = "Sir"
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(obj);
Then wrote the 'output' variable to file. 然后将“输出”变量写入文件。 Thanks for the help :) 谢谢您的帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.