开发者

ASP.NET MVC2 InputHelper and List.Insert() strange behavior

I cannot make sense of this...

The simplified code below OUGHT to insert a new form field of the current time's second value.

Instead, even though the list manipulation happens correctly (as verifiable within the controller and in the debug output), the View does render an additional element, but seems to be just a copy of the final field's value (prior to submit). This can be verified by changing a field prior to submit - the values stick and the new element is a duplicate of the submitted final value.

The part that really cooks my noodle is that if I trivially change the operation from an Insert() to an Add(), the Add() works as expected!!

Using this example Model:

public class MyViewData
{
  List<string> stringData = new List<string>();
  public List<string> StringData { get { return stringData; } }
}

And this Controller:

public class TestController : Controller
{
  public ActionResult Index()
  {
    return View(new MyViewData());
  }

  [HttpPost]
  public ActionResult Index(MyViewData data)
  {
    data.StringData.Insert(0, DateTime.Now.Second.ToString());

    return View(data);
  }
}

And this View:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage&l开发者_如何转开发t;Forms.Controllers.MyViewData>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Test
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%      
        System.Diagnostics.Debug.WriteLine("---");
        for (var i = 0; i < Model.StringData.Count; i++)
            System.Diagnostics.Debug.WriteLine("{0}", Model.StringData[i]);
    %>

    <% using (Html.BeginForm()) { %>

        <% for (var i = 0; i < Model.StringData.Count; i++) { %>

            <%: Html.TextBoxFor(model => model.StringData[i])%></br>

        <% } %>

        <div><input type="submit" value="Do it" /></div>

    <% } %>
</asp:Content>


This is the normal behavior of standard HTML helpers and is by design. When rendering the input field they will first look at the request POSTed values and only after in the ViewData and view model. This basically means that you cannot change POSted values in your controller action.

So if you have a form with an input field:

<%= Html.TextBoxFox(x => x.Id) %>

which is posted to the following action

[HttpPost]
public ActionResult Index(MyModel model)
{
    model.Id = "some new value";
    return View(model);
}

when rendering the view back the html helper will use the posted value. You could either write a custom html helper that does the job for you or handle it manually (absolutely not recommended but for the record):

<input type="text" name="StringData[<%= i %>]" value="<%= Model.StringData[i] %>" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜