【发布时间】:2017-11-02 09:53:44
【问题描述】:
我有一个 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。 有什么指点吗?
【问题讨论】:
-
或
JavaScriptSerializer或json.net?所有这些都会为你正确地序列化你的模型。 -
我不想将整个模型发送给客户。像这样编写它的唯一原因是避免创建另一个对象,该对象与另一个知道有多少相似的对象略有不同。但如果这是推荐的方式,那么这就是我要做的。不过,我很想知道如何做到这一点。
-
如果您不想定义另一个显式类型,只需序列化一个适当的anonymous type。
-
@dbc 完美,谢谢,成功了。我应该发布我要工作的代码吗? (评论或回复?)
标签: c# asp.net json asp.net-mvc