MVC5 Lost value in Textbox after Submit

2019-07-20 21:28发布

问题:

I would like to clarify one thing about MVC5 Razor Views.

I was told that I don't have to use HTML Helpers (@Html.EditorFor, @Html.TextBoxFor) in my razor views and it will still work.

Controller Code

[HttpPost]
        public ActionResult Create(Models.TestObj obj)
        {
            ViewBag.TestStr = string.Format("You typed: {0} {1}", obj.FirstName, obj.LastName);
            return View(obj);
        }

Razor View

@using (Html.BeginForm())
{

        <div>
            @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control", style = "width: 120px;" } })     
            <input class="form-control text-box single-line" id="LastName" name="LastName" style="width: 120px;" type="text">       
            <input type="submit" name="submit" value="Filter" / >
        </div>


    @ViewBag.TestStr
}

But when I actually test it like the above, the value typed in 'LastName' textbox is not preserved. I can catch both textbox values in my Controller. But after postback, lost the value in 'LastName' textbox. The textbox which is created by using HTMLHelper didn't lose the value though.

Am I doing something wrong or is it supposed to be like that? Do I have to use HtmlHelpers in RazorViews in MVC5 if I want to keep the submitted values?

回答1:

Your not binding the second input to the value of LastName, just setting its name attribute. If you inspect the html you generating, you will note the first one has a value attribute whereas the second does not.

You need to use the EditorFor() (or TextBoxFor()) as you did for the FirstName which generates the correct value attribute (and other data-val-* attributes necessary for using client side validation).

Side note: You could also use

<input name="LastName" ..... value="@Model.LastName"` />

however this will not take into account ModelState values



回答2:

What's a "postback"? It sounds like you're trying to think of this in terms of WebForms, where the server-side controls have a lot of plumbing doing things behind the scenes.

Simply put, there is no code in your view which actually puts a value in that input. When using the HTML helpers, while the generated client-side markup is the same (and, thus, the post to the next controller action is the same), one thing that's different is that the HTML helpers will bind the control to the model that's supplied to the view.

HTML, by itself, won't do that. You can, however, do that manually:

<input value="@Model.LastName" class="form-control text-box single-line" id="LastName" name="LastName" style="width: 120px;" type="text">       
       ^--- right here