简体   繁体   English

MVC ViewModel未在View中填充

[英]MVC ViewModel not populating in View

I am trying to take an input from a text box, replace some strings within it - and return both the original and the replacement strings to the View, and populate two separate text boxes. 我试图从文本框中取一个输入,替换其中的一些字符串 - 并将原始和替换字符串返回到视图,并填充两个单独的文本框。

My simple view model is: 我的简单视图模型是:

public class WordsToConvert
{
    public string Original { get; set; }
    public string Replacement { get; set; }
}

My cshtml file has a form, which is the same form I would like populated when the Post returns to the same view: 我的cshtml文件有一个表单,当Post返回到同一视图时,它与我想要填充的表单相同:

            @Html.EditorFor(model => model.Original, 
                  new { htmlAttributes = new { @class = "form-control" } })

            @Html.EditorFor(model => model.Replacement, 
                  new { htmlAttributes = new { @class = "form-control" } })

My controller is very simple (just to get started): 我的控制器非常简单(只是为了开始):

    // 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);
    }

I can see wordsToConvert.Replacement changing in the Watch window in VS - but when the View displays it again, it's blank. 我可以在VS的Watch窗口中看到wordsToConvert.Replacement更改 - 但是当View再次显示它时,它是空白的。

If I add @Model.Replacement to the view - then I can see the updated "original" with "Test - xxxxx" at the front. 如果我将@ Model.Replacement添加到视图中 - 那么我可以在前面看到更新的“原始”和“Test - xxxxx”。

Is there anything I can do to get the Replacement text to show in the replacement textbox/EditorFor? 有什么办法可以让替换文本显示在替换文本框/ EditorFor中吗?

Thanks, Mark 谢谢,马克

This is a well known gotcha in MVC. 这是MVC中众所周知的问题。

ModelState.Clear();

Will fix the issue. 将解决问题。 You can also do it individually if you want to target just one field: 如果您只想定位一个字段,也可以单独执行此操作:

ModelState.Remove("Replacement");

The reason is complicated, and has to do with a choice the MVC team made to try and do the right thing most of the time for people (but sometimes this is the wrong thing for some people). 原因很复杂,并且与MVC团队在大多数情况下为人们做出正确的事情所做的选择有关(但有时这对某些人来说是错误的)。

http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM