0

I have the two classes below. I can do a screen to enter data, and get the data ProdutoPadrao and ProdutoPadraoCaracteristica, by model and List.

I want to show data from the ProdutoPadrao and ProdutoPadraoCaracteristica list, but how do I retrieve the items with their Descricao and TipoCaracteristicaID, to edit the values​​ in database.

Show on the screen I know, doing a foreach and using RenderPartial, and creating their TextFor, but how to retrieve it in a POST FORM.

But how to do this on a screen editing?

The screen is more or less like this:

enter image description here

Model

public class ProdutoPadrao : IEntidadeBase
{
  [Key]
  public int ProdutoPadraoID { get; set; }
  [Display(Name = "Descrição")]
  public string Descricao { get; set; }
  [Display(Name = "Detalhe")]
  public string Detalhe { get; set; } 
  public virtual ICollection<ProdutoPadraoCaracteristica> ListaProdutoCaracteristica { get; set; }    
}

public class ProdutoPadraoCaracteristica : IEntidadeBase
{
  [Key]
  public int ProdutoPadraoCaracteristicaID { get; set; }
  public int ProdutoPadraoID { get; set; }
  public string Descricao { get; set; }
  public int TipoCaracteristicaID { get; set; }    
  [ForeignKey("ProdutoPadraoID")]
  public virtual ProdutoPadrao ProdutoPadrao { get; set; }
}    

Controller GET

[ControleDeAcesso(TipoAcao.Normal)]
[Authorize]
public ActionResult Detalhar(int id)
{
    using (var db = new ERPContext())
    {
        var produtoPadrao = db.ProdutoPadrao.Include("ListaProdutoCaracteristica").Where(w => w.ProdutoPadraoID == id).ToList().FirstOrDefault();
        var retorno = EntidadeBaseExt.ValidarRegistro(produtoPadrao, TipoAcao.Visualizar);
        if (retorno != "")
        {
            TempData["MsgRetornoError"] = retorno;
            return RedirectToAction("Index", "Home");
        }
        ViewBag.ListaCaracteristica = new SelectList(ListagemPadrao.ListaTipoCaracteristica(), "Key", "Texto");
        ViewBag.ListaUnidadeMedida = new SelectList(db.UnidadeMedida.ToListERP().Select(l => new ItemLPesquisa { Key = l.UnidadeMedidaID, Texto = l.Descricao }).ToArray(), "Key", "Texto");
        return View(produtoPadrao);
    }
}

Controller POST

[Authorize]
[HttpPost]
[ControleDeAcesso(TipoAcao.Normal)]
public ActionResult Detalhar(string btnSubmit, ProdutoPadrao model)
{
    if (!ModelState.IsValid)
    {                
        return View(model);
    }

    using (var db = new ERPContext())
    {
        var produtoPadrao = db.ProdutoPadrao.Include("ListaProdutoCaracteristica").Where(w => w.ProdutoPadraoID == model.ProdutoPadraoID).ToList().FirstOrDefault();
        var retorno = FlexGestor.Helpers.EntidadeBaseExt.ValidarRegistro(produtoPadrao, TipoAcao.Gravar);
        if (retorno != "")
        {
            TempData["MsgRetornoError"] = retorno;
            return RedirectToAction("Index", "Home");
        }
        model.ListaProdutoCaracteristica = null;
        if (btnSubmit != "Excluir")                
            UpdateModel(produtoPadrao);

        FlexGestor.Helpers.EntidadeBaseExt.AtribuirValores(produtoPadrao, btnSubmit);
        db.Entry(produtoPadrao).State = EntityState.Modified;
        db.SaveChanges();

        if (btnSubmit == "Excluir")
            return RedirectToAction("Index", controller);

        return RedirectToAction("Detalhar", controller, new { id = model.ProdutoPadraoID });
    }
}

View Master

@model FlexGestor.Models.ProdutoPadrao


@using (Html.BeginForm())
{
    <div class="row">                
        @Html.TituloPagina("Visualizando Produto Padrão", "Clique para abrir a ajuda", "#help_produtoPadrao")
        @Html.HiddenFor(m => m.ProdutoPadraoID)
        <div class="col-md-12">
            @Html.LabelFor(m => m.Descricao) @Html.ValidationMessageFor(m => m.Descricao)
            @Html.TextBoxFor(m => m.Descricao, new { @class = "form-control" })
        </div>
        <div class="col-md-12">
            @Html.LabelFor(m => m.Detalhe) @Html.ValidationMessageFor(m => m.Detalhe)
            @Html.TextAreaFor(m => m.Detalhe, new { @class = "form-control", @rows = "4" })
        </div>

    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ListaProdutoCaracteristica)
        <div class="controls">
            <ul id="PhonesEditor" style="list-style-type: none">
                @if (Model.ListaProdutoCaracteristica != null)
                {
                    foreach (var item in Model.ListaProdutoCaracteristica)
                    {
                        Html.RenderPartial("_CustomerPhonesEditor", item);
                    }
                }
            </ul>
        </div>
        <p><a id="addAnother" class="small-button">AddPhone</a></p>
    </div>

    <div class="row">        
        <div class="col-md-12">
            @Html.BotaoTelaDetalhar()
        </div>
    </div>
}

View Datail

@model FlexGestor.Models.ProdutoPadraoCaracteristica



    @Html.HiddenFor(m => m.ProdutoPadraoID)
    @Html.HiddenFor(m => m.ProdutoPadraoCaracteristicaID)

    <div class="col-md-3">
        @Html.LabelFor(m => m.TipoCaracteristicaID) @Html.ValidationMessageFor(m => m.TipoCaracteristicaID)
        @Html.DropDownList("TipoCaracteristicaID", (SelectList)ViewBag.ListaCaracteristica, String.Empty,
                      new { @class = "form-control" })
    </div>

    <div class="col-md-9">
        @Html.LabelFor(m => m.Descricao) @Html.ValidationMessageFor(m => m.Descricao)
        @Html.TextBoxFor(m => m.Descricao, new { @class = "form-control" })
    </div>

    <div class="form-group">
        <div class="controls">
            <a onclick="$(this).parent().parent().parent().remove();" class="small-button" style="float: left;">Delete</a>
        </div>
    </div>
mtsys
  • 249
  • 1
  • 4
  • 15
  • You need to post your code for the controller methods (GET and POST) and the view (not the image) –  Aug 28 '14 at 23:56
  • @StephenMuecke add post and get and view – mtsys Aug 29 '14 at 00:13
  • When you post, is the `ListaProdutoCaracteristica` property of `ProdutoPadrao` null? –  Aug 29 '14 at 00:37
  • @StephenMuecke sorry did not understand – mtsys Aug 29 '14 at 01:38
  • Put a breakpoint on the first line of the the post method and inspect the value of the `model` parameter - is its property `ListaProdutoCaracteristica` null? (I am trying to determine if the data is posting correctly) –  Aug 29 '14 at 01:43
  • Yes, is null, was using BeginCollectionItem HtmlHelper but was giving much trouble – mtsys Aug 29 '14 at 01:48
  • You not using the loop correctly and as a result the `` name attributes do not match your property names. I'll post an answer shortly. –  Aug 29 '14 at 01:53

1 Answers1

1

The values of the collection ProdutoPadraoCaracteristica are null on post back because your foreach loop is not naming the controls correctly. Create an editor template ProdutoPadraoCaracteristica.cshtml in the Views/Shared/EditorTemplates folder and copy the code from the _CustomerPhonesEditor partial view.

Then modify the loop to use the editor template, so instead of

<div class="controls">
  <ul id="PhonesEditor" style="list-style-type: none">
    @if (Model.ListaProdutoCaracteristica != null) {
      foreach (var item in Model.ListaProdutoCaracteristica) {
        Html.RenderPartial("_CustomerPhonesEditor", item);
      }
    }
  </ul>
</div>

just use

@Html.EditorFor(m => m.ListaProdutoCaracteristica)

this should generate elements such as

<input type="hidden" name="ListaProdutoCaracteristica[0].ProdutoPadraoID" ...>
<input type="hidden" name="ListaProdutoCaracteristica[1].ProdutoPadraoID" ...>

etc, which will post back correctly

  • Hi MTSYS.Can you post the JS for the addAnother button please? – Richard Aug 07 '15 at 15:35
  • @user1295445, Unclear what your asking. Best guess is you want something like [this](http://stackoverflow.com/questions/28019793/submit-same-partial-view-called-multiple-times-data-to-controller/28081308#28081308) or [this](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796). If not, you need to ask your own question. –  Aug 07 '15 at 23:37