tags:

views:

45

answers:

1

I have the following code in my view

    <% foreach (var item in Model.stats)
       {%> 
       <label style="style="float:left;"><%= item.Stat_Caption %></label>
       <%=Html.TextBox(item.Stat_Caption,item.Stat_Value) %>

       <%} %>

I'm trying to turn my stats object which is just a list collection, into a list of textboxes so the user can update them.

which i have got working, how do i once the user updates the textboxes apply the values back to the list collection?

+4  A: 

You need to wrap the textboxes in a form:

<% using (Html.BeginForm()) { %>
    <% foreach (var item in Model.stats)
       {%> 
       <label style="style="float:left;"><%= item.Stat_Caption %></label>
       <%=Html.TextBox(item.Stat_Caption,item.Stat_Value) %>

       <%} %>

    <input type="submit" value="Save" class="button" /></td>
<% } %>

When you press the submit button, it will do a standard POST with key/value pairs like so:

Box1 : Hello
Box2 : World

On the controller side, you need to have a method that receives the POST request:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Entity entity)
{
    // code goes here
}

where Entity is your data model object. The default MVC model binder uses reflection to populate your entity's fields, so if the entity was like this:

public class Entity()
{
    public string Box1 { get; set; }
    public string Box2 { get; set; }
}

Then Box1 and Box2 will be set to the values that were sent in the POST request.

If you don't have an entity, then you can use this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
    // code goes here
}

where collection is a dictionary of objects. The bad thing with using this dictionary is that it's a dictionary of Object types, so you'll have to grab the data and cast it back to whatever type it's supposed to be.

Daniel T.
thank you for taking the time! great explanation!!
Howlingfish