views:

357

answers:

1

I am getting some unexpected behavior from Html.EditorFor().

I have this controller:

[HandleError]
public class HomeController : Controller
{
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Lister()
    {
        string[] values = { "Hello", "world", "!!!" };

        return View(values);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Lister(string[] values)
    {
        string[] newValues = { "Some", "other", "values" };

        return View(newValues);
    }
}

And this is my view which is intended to work for both of these:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<string[]>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Lister
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Lister</h2>

    <% using (Html.BeginForm()) { %>
        <% foreach (string value in Model) { %>
            <%= value %><br />
        <% } %>
        <%= Html.EditorForModel() %>
        <input type="submit" value="Append Dashes" />
    <% } %>

</asp:Content>

And the problem is that when the post back is made from the view, it hits the correct action, but the text boxes still show the original hello world data while the foreach loop outputs the new values. It feels like something in ASP.NET is overriding my model values from updating the text boxes and they are just displaying the same old values.

I found this issue while trying to learn EditorFor with an IEnumerable.

+1  A: 

This is not a problem, it is the normal behavior. All helpers work that way. They first look at posted values and then the model in order to perform the binding. That is to say even if you modify the model in your controller action, they will use the initial posted values.

Related questions:

Darin Dimitrov
Well thats a bit annoying for my purpose, do you happen to have a link to documentation for that?
NickLarsen
I am not sure whether this is a documented behavior. The second link I provided is an answer from Phil Haack which should be more than enough :-)
Darin Dimitrov