Question

I have a string array called Groups containing the following two strings

  1. Group Alpha
  2. Group Bravo

Controller

public ActionResult Task(TaskModel model)
{

    return PartialView(model);
}

Index view which invokes my Task action

<div id="update">

    @using (Ajax.BeginForm("Task", "Home", new AjaxOptions { UpdateTargetId = "update", InsertionMode = InsertionMode.Replace}))
    {

        <input value="Group Alpha" name="Groups"/>
        <input value="Group Bravo" name="Groups"/>

        <button type="submit">Submit</button>
    }

</div>

My task view

@model MvcApplication4.Models.TaskModel

<div id="container">

        @if (Model.Groups != null)
        {

            foreach (var group in Model.Groups)
            {

                @Html.TextBox("Groups", group, new { @id = String.Empty })                                                         

            }
        } 
</div>

my task model

public class TaskModel : IValidatableObject
{
    public Guid TaskId { get; set; }
    public String Name { get; set; }

    public string[] Groups { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {

        yield break;
    }
}

This only outputs Group Alpha Group Alpha. Wheres the problem??

Sorry for not being clear before

Example project replicating the issue https://www.dropbox.com/s/s2o59cu00am3eov/MvcApplication4.zip

Was it helpful?

Solution

You POST some input fields named Groups. In the action method processing that POST, you render a partial that uses @Html.TextBox("Groups", ...).

@Html.TextBox uses the ModelState to fill the value with the previously POSTed value, based on input element name. In this case it takes the first Groups value it finds in the POST, being "Group Alpha".

Clear the ModelState (or just the Groups key) before rendering your partial view.

This:

ModelState.Clear();
ModelState.Remove("Groups");

return PartialView(model);

Works.

Next time try showing all relevant code up front, so we don't need so many comments asking you to. :-)

OTHER TIPS

This is a closure problem I think. Try this code:

<div id="container">

    @if (Model.Groups != null)
    {
        foreach (var group in Model.Groups)
        {
            var currentGroup = group;
            @Html.TextBox("Groups", currentGroup, new {@id = String.Empty});
        }
    } 
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top