开发者

How to interact with List<t> in MVC

开发者 https://www.devze.com 2022-12-21 06:02 出处:网络
I have the following code in my view <% foreach (var item in Model.stats) {%> <label style=\"style=\"float:left;\"><%= item.Stat_Caption %></label>

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?


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.

0

精彩评论

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

关注公众号