Tengo @Ajax.BeginForm en cada fila de la tabla, cuando hago una solicitud de publicación usando ese formulario, el modelo es nulo excepto la primera fila

Tengo @Ajax.BeginForm en cada fila de la tabla. Cuando hago una solicitud de publicación usando ese formulario, el modelo es nulo excepto la primera fila.

Solo funciona el primer formulario, el segundo y así sucesivamente no funcionan.... He usado el ID de formulario único para todos.

Probablemente, debido a que estoy usando IList y bucles for,

Y la primera forma tiene un nombre de control como [0].lstMatches[4].match_set_name y la segunda, tercera,.... forma tiene un nombre de control como [n].lstMatches[4].match_set_name

e IList puede proporcionar el modelo solo para el primero, [0].lstMatches[4].match_set_name

Aquí está mi estructura de vista

  @model IList<QIOnlineMVC3.Models.TravelAdsRulesMatchsGroups>
@{
ViewBag.Title = "Business Rule Travel Ads";
ViewBag.Layout = "_Layout2";
 }

 <table id="PageSortTable" class="travelads_business_rules" cellspacing="0">
<tr></tr>
 <tbody>
@for (var i = 0; i < Model.Count; i++)
    {
<tr class="minimised" id='trMinimised@(Model[i].id)'>
            <td colspan="13">
                @using (Ajax.BeginForm("_SaveGroupMatchs", null, new AjaxOptions { OnSuccess = "onSuccess", UpdateTargetId = "msgResult", LoadingElementId = "msgLoading", HttpMethod = "Post" }, new { @id = "SaveForm" + Model[i].id.ToString() }))
                {  
 <div class="detail">
  <div class="table_header">
                        <span class="col_a">Group</span> <span class="col_b">Group Scope</span> <span class="col_c">
                            Seq</span> <span class="col_d">&nbsp;</span> <span class="col_e">ID</span> <span
                                class="col_f">Match Location</span> <span class="col_g">Target Field</span>
                        <span class="col_h">Match Type</span> <span class="col_i">Set Name</span>
                    </div>
                    <!-- Loop for matches -->
                    <!-- start GROUP -->
                    <div class="group" id="Group_rule_@(Model[i].id)">

                       @Html.HiddenFor(model => @Model[i].id)
                       @Html.HiddenFor(model => @Model[i].ad_rule_name)
                       @Html.HiddenFor(model => @Model[i].ad_rule_desc)
                       @Html.HiddenFor(model => @Model[i].business)
                       @Html.HiddenFor(model => @Model[i].ad_region)
                       @Html.HiddenFor(model => @Model[i].ad_form)
                       @Html.HiddenFor(model => @Model[i].ad_company)
                       @Html.HiddenFor(model => @Model[i].ad_team)
                       @Html.HiddenFor(model => @Model[i].ad_language)
                       @Html.HiddenFor(model => @Model[i].ad_media_id)
                       @Html.HiddenFor(model => @Model[i].ad_insert_loc)
                       @Html.HiddenFor(model => @Model[i].ad_priority)
                       @Html.HiddenFor(model => @Model[i].access)
                       @Html.HiddenFor(model => @Model[i].deployment)


                        @for (var j = 0; j < Model[i].lstMatches.Count; j++)
                        {
                            <div id="rule@(Model[i].id)_divRuleGroup_@(Model[i].lstMatches[j].match_group_num)">
                             @Html.HiddenFor(model => Model[i].lstMatches[j].match_rule_id)
                             @Html.HiddenFor(model => Model[i].lstMatches[j].match_id)
                             @Html.HiddenFor(model => Model[i].lstMatches[j].match_group_num)
                             @Html.HiddenFor(model => Model[i].lstMatches[j].match_rule_type)
                             @Html.HiddenFor(model => Model[i].lstMatches[j].created)
                             @Html.HiddenFor(model => Model[i].lstMatches[j].access)
                            <header id="header_rule_Group"><span class="col_a">
                             @if (Model[i].lstMatches[j].Position == "First")
                             {
                                @(Model[i].lstMatches[j].match_group_num) 
                             } </span>
                            <span class="col_b">
                                            @if (Model[i].lstMatches[j].Position == "First")
                                            {
                                            @Html.DropDownListFor(model => Model[i].lstMatches[j].match_group_scope, new SelectList((List<QIOnlineMVC3.Helpers.clsGroupScope>)QIOnlineMVC3.Helpers.General.GetALLGroupScope(), "GroupScope", "GroupScope", Model[i].lstMatches[j].match_group_scope))
                                            }
                                            else
                                            {
                                                @Html.HiddenFor(model => Model[i].lstMatches[j].match_group_scope)
                                            }
                                          </span></header>
                            <div class="match">
                                <span class="col_c">@(Model[i].lstMatches[j].match_group_seq) @Html.HiddenFor(model => Model[i].lstMatches[j].match_group_seq) </span> 
                                <span class="col_d">
                                <a href="@(Url.Action("DeleteMatch", new { id = Model[i].lstMatches[j].match_id }))">
                                    <img alt="Delete" src="../../Content/Images/delete-icon.png" width="17" height="17" border="0" title="delete" /></a> 

                                        </span><span class="col_e">@(Model[i].lstMatches[j].match_id)
                                        </span><span class="col_f">
                                            @Html.DropDownListFor(model => Model[i].lstMatches[j].match_loc, new SelectList((List<QIOnlineMVC3.Helpers.clsMatchLocations>)QIOnlineMVC3.Helpers.General.GetALLMatchLocations(), "MatchLocations", "MatchLocations", Model[i].lstMatches[j].match_loc))
                                        </span><span class="col_g">
                                            @Html.DropDownListFor(model => Model[i].lstMatches[j].match_target_field, new SelectList((List<QIOnlineMVC3.Helpers.clsTargetField>)QIOnlineMVC3.Helpers.General.GetALTargetField(), "TargetField", "TargetField", Model[i].lstMatches[j].match_target_field))
                                        </span><span class="col_h">
                                            @Html.DropDownListFor(model => Model[i].lstMatches[j].match_type, new SelectList((List<QIOnlineMVC3.Helpers.clsMatchType>)QIOnlineMVC3.Helpers.General.GetALLMatchType(), "MatchTypeID", "MatchType", Model[i].lstMatches[j].match_type))
                                        </span><span class="col_i">
                                            @Html.TextBoxFor(model => Model[i].lstMatches[j].match_set_name, new { @value = Model[i].lstMatches[j].match_set_name, @class = "clsauto" })
                                            </span></div>
                            </div>


                                       if (Model[i].lstMatches[j].Last == "Last")
                                       {
                            <div id="Group_rule_@(Model[i].id)_@(Model[i].lstMatches[j].match_group_num)"></div>
                            <!-- end MATCH -->
                            <div class="new">
                                @Ajax.ImageWithTextActionLink("<img src=\"../../Content/Images/new-icon.png\" width=\"17\" height=\"17\" border=\"0\" alt=\"New Match\" />New Match", "NewMatch", new { ruleid = Model[i].id, groupid = Model[i].lstMatches[j].match_group_num }, new AjaxOptions { UpdateTargetId = "Group_rule_" + Model[i].id.ToString() + "_" + Model[i].lstMatches[j].match_group_num, InsertionMode = InsertionMode.InsertBefore, HttpMethod = "Get", LoadingElementId = "msgLoading" })
                            </div>
                                       }

                        }

                    </div>
                    <!-- end MATCH GROUP -->
                    <!-- END Loop of Matches -->
                    <div class="new new_group">
                        @Ajax.ImageWithTextActionLink("<img src=\"../../Content/Images/new-icon.png\" width=\"17\" height=\"17\" border=\"0\" alt=\"New Group\" />New Group</a>", "NewGroup", new { ruleid = Model[i].id }, new AjaxOptions { UpdateTargetId = "Group_rule_" + Model[i].id.ToString(), InsertionMode = InsertionMode.InsertAfter, HttpMethod = "Get", LoadingElementId = "msgLoading" })
                        <div class="delete_group">
                            Delete Group ID:
                            <input type="text" id='txtdeleteGroupNo_@(Model[i].id)' />
                            <input type="submit" id='btnDeleteGroup_@(Model[i].id)' value="Delete Group" class="btn btn_delete" style="float: none;" onclick="return DeleteGroup(this);" />
                        </div>
                    </div>
                    <div id="divNewGroup">
                    </div>
                    <div class="btn_row">
                        <input type="reset" name="reset" class="btn" value="Cancel" onclick='DoExpandCollapsh("trMinimised@( Model[i].id)","main_collapsed@( Model[i].id)","main_expanded@( Model[i].id)")'/>
                        <input type="submit" name="btnSave" class="btn" value="Save" />
                        <a href="@(Url.Action("DeleteTravelAdsRule", new { id = Model[i].id }))" class="btn btn_delete">
                            Delete Rule</a>
                    </div>
                </div>
                }

            </td>
        </tr>

    }
</tbody>

Aquí está mi controlador

    [Authorize]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult _SaveGroupMatchs(IList<TravelAdsRulesMatchsGroups> mm)
    {
        try
        {
            if (mm != null & mm.Count > 0)
            {

                foreach (var item in mm)
                {
                    List<MatchModel> LMM = item.lstMatches.ToList();
                    List<MatchModel> LMMUpdate = LMM.Where(t => t.match_id != 0).ToList();
                    //update 
                    foreach (var mmupdate in LMMUpdate)
                    {
                        UpdateMatch(mmupdate);
                    }
                    List<MatchModel> LMMSave = LMM.Where(t => t.match_id == 0).ToList();
                    //save
                    foreach (var itemSave in LMMSave)
                    {
                        itemSave.access = item.access;
                        itemSave.deployment = item.deployment;
                        itemSave.match_deployment = item.deployment;
                        CreateMatch(itemSave);
                    }
                }
            }
        }
        catch { Content("Problem due to Error"); }

        return Content("Record Saved Successfully!");
    }

No obtengo IList para el segundo y así sucesivamente...

Como puedo conseguirlo, alguna idea?

preguntado el 31 de julio de 12 a las 10:07

También lo publiqué en el foro asp.net, pero aún no tuve suerte ... foros.asp.net/t/1829267.aspx/… -

1 Respuestas

Bueno, realmente no entiendo lo que te gustaría hacer.

  • Si desea guardar la lista completa de TravelAdsRulesMatchsGroups
    Use solo UN formulario que llame a su _SaveGroupMatchs método de acción

  • Si desea guardar solo uno TravelAdsRulesMatchsGroups (un botón de envío para cada registro),
    sigue usando uno form por fila y cambie la acción de su controlador a

    public ActionResult _SaveGroupMatchs(TravelAdsRulesMatchsGroups mm)
    

    luego adapte su método de acción para manejar la grabación de una instancia de TravelAdsRulesMatchsGroups

    Y, en su opinión, no use

    @Html.HiddenFor(model => model[i].Id)
    

    Si usa esta sintaxis, el Html renderizado será <input ... name="[i].Id" />
    (p.ej. <input ... name="[2].Id" />)

    El encuadernador de modelos utiliza el name para llenar las propiedades de su modelo

    En su lugar, use

    @* for your TravelAdsRulesMatchsGroups properties *@
    @Html.Hidden("id", Model[i].id)
    @* ... and so on ...*@
    
    
    @* for the lstMatches property, which is a list of MatchModel *@
    @for (var j = 0; j < Model[i].lstMatches.Count; j++)
    {
        @Html.Hidden("lstMatches[" + j.ToString() + "].match_rule_id", Model[i].lstMatches[j].match_rule_id)
        @* ... and so on ...*@
    }
    

Nota: tenga cuidado, ¡no puede usar formularios Html anidados!

Respondido 03 ago 12, 11:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.