MVC ViewModel 未在视图中填充
MVC ViewModel not populating in View
我正在尝试从文本框中获取输入,替换其中的一些字符串 - return 将原始字符串和替换字符串都添加到视图中,然后填充两个单独的文本框。
我的简单视图模型是:
public class WordsToConvert
{
public string Original { get; set; }
public string Replacement { get; set; }
}
我的 cshtml 文件有一个表单,当 Post returns 到相同的视图时我想要填充的表单是相同的:
@Html.EditorFor(model => model.Original,
new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.Replacement,
new { htmlAttributes = new { @class = "form-control" } })
我的控制器非常简单(刚开始):
// POST: WTC
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult WTC([Bind(Include = "Original,Replacement")] WordsToConvert wordsToConvert)
{
if (ModelState.IsValid)
{
wordsToConvert.Replacement = "Test " + wordsToConvert.Original;
return View(wordsToConvert); // <---- at this point Watch shows wordsToConvert.Replacement as "Test whatever other text"
}
return View(wordsToConvert);
}
我可以看到 wordsToConvert.Replacement 在 VS 中的 Watch window 中发生变化 - 但是当视图再次显示它时,它是空白的。
如果我将 @Model.Replacement 添加到视图中 - 那么我可以看到更新后的 "original" 和前面的 "Test - xxxxx"。
我可以做些什么来让替换文本显示在替换中 textbox/EditorFor?
谢谢,马克
这是 MVC 中众所周知的陷阱。
ModelState.Clear();
将解决问题。如果您只想定位一个字段,也可以单独执行此操作:
ModelState.Remove("Replacement");
原因很复杂,这与 MVC 团队做出的选择有关,即尝试在大多数时间为人们做正确的事情(但有时这对某些人来说是错误的事情)。
我正在尝试从文本框中获取输入,替换其中的一些字符串 - return 将原始字符串和替换字符串都添加到视图中,然后填充两个单独的文本框。
我的简单视图模型是:
public class WordsToConvert
{
public string Original { get; set; }
public string Replacement { get; set; }
}
我的 cshtml 文件有一个表单,当 Post returns 到相同的视图时我想要填充的表单是相同的:
@Html.EditorFor(model => model.Original,
new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.Replacement,
new { htmlAttributes = new { @class = "form-control" } })
我的控制器非常简单(刚开始):
// POST: WTC
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult WTC([Bind(Include = "Original,Replacement")] WordsToConvert wordsToConvert)
{
if (ModelState.IsValid)
{
wordsToConvert.Replacement = "Test " + wordsToConvert.Original;
return View(wordsToConvert); // <---- at this point Watch shows wordsToConvert.Replacement as "Test whatever other text"
}
return View(wordsToConvert);
}
我可以看到 wordsToConvert.Replacement 在 VS 中的 Watch window 中发生变化 - 但是当视图再次显示它时,它是空白的。
如果我将 @Model.Replacement 添加到视图中 - 那么我可以看到更新后的 "original" 和前面的 "Test - xxxxx"。
我可以做些什么来让替换文本显示在替换中 textbox/EditorFor?
谢谢,马克
这是 MVC 中众所周知的陷阱。
ModelState.Clear();
将解决问题。如果您只想定位一个字段,也可以单独执行此操作:
ModelState.Remove("Replacement");
原因很复杂,这与 MVC 团队做出的选择有关,即尝试在大多数时间为人们做正确的事情(但有时这对某些人来说是错误的事情)。