Problems saving a selected item in Dropdownlistfor using a ViewModel

0

I'm trying to save a change I try to make by selecting a Category in a Dropdownlistfor .

Type like this:

I'mfollowingtheDebugandtheViewissendingtheselectedCategory,butIcannotcontinuethischange.

MySubcategoryControllerlookslikethis:

//GET:SubCategorias/Edit/5publicActionResultEdit(Guid?id){if(id==null)returnnewHttpStatusCodeResult(HttpStatusCode.BadRequest);SubCategoriaViewModelsubCategoriaViewModel=_subCategoriaAppService.ObterPorId(id.Value);subCategoriaViewModel.Categorias=_categoriaAppService.ObterTodas();if(subCategoriaViewModel==null)returnHttpNotFound();returnView(subCategoriaViewModel);}//POST:SubCategorias/Edit/5[HttpPost][ValidateAntiForgeryToken]publicActionResultEdit(SubCategoriaViewModelsubCategoriaViewModel){_subCategoriaAppService.Atualizar(subCategoriaViewModel);returnRedirectToAction("Index");
    }

My method for updating looks like this:

public SubCategoriaViewModel Atualizar(
        SubCategoriaViewModel subCategoriaViewModel)
    {
        //var categoriaSelecionada =
        //     _categoriaService.ObterPorId(subCategoriaViewModel.CategoriaId);
        subCategoriaViewModel.Categoria =
            _categoriaService.ObterPorId(subCategoriaViewModel.CategoriaId);

        var subCategoria =
            Mapper.Map<SubCategoriaViewModel,
            SubCategoria>(subCategoriaViewModel);

        //subCategoria.Categoria = categoriaSelecionada;
        _subCategoriaService.Atualizar(subCategoria);

        return subCategoriaViewModel;
    }

In my View :

<div class="form-group">
        @Html.LabelFor(model => model.Categoria, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.CategoriaId,
           new SelectList(Model.Categorias, "CategoriaId", "CategoriaNome"), new { @class = "form-control" })              
        </div>
    </div>

My ViewModel

public class SubCategoriaViewModel
{
    public SubCategoriaViewModel()
    {
        SubCategoriaId = Guid.NewGuid();
    }

    [Key]
    public Guid SubCategoriaId { get; set; }

    [Required(ErrorMessage = ("Preencha o nome da SubCategoria."))]
    [MaxLength(60, ErrorMessage = ("Máximo {0} caracteres."))]
    [MinLength(1, ErrorMessage = ("Mínimo {0} caracteres."))]
    [DisplayName("Nome")]
    public string SubCategoriaNome { get; set; }

    public IEnumerable<CategoriaViewModel> Categorias = new List<CategoriaViewModel>();
    public Guid CategoriaId { get; set; }

    //[ScaffoldColumn(false)]
    //public DomainValidation.Validation.ValidationResult ValidationResult { get; set; }

    public virtual Categoria Categoria { get; set; }
    //public ICollection<Produto> Produtos { get; set; }

}

The interesting thing is that if I modify the name of the SubCategory it persisted! Anything, this is the way of how I'm trying to persist it link

    
asked by anonymous 22.02.2017 / 17:37

2 answers

1

After much conversation with two good-hearted people ( Tiago Silva and LP Gonçalves ), we were able to understand the problem.

The problem was how I was handling the Membership Type to save and / or change my entities in the database using the Entity Framework .

Before the solution, I was using Independent Association which was one of the first forms of association between entities and that used object orientation to make this association. As you may know, I was misusing the feature. So in the conversation with Tiago Silva he explained the error and why it would be better to use Foreign Key ) .

What has changed is my application class, which now looks like this:

public SubCategoriaViewModel Atualizar(
        SubCategoriaViewModel subCategoriaViewModel)
    {
        var categoriaSelecionada =
             _categoriaService.ObterPorId(subCategoriaViewModel.CategoriaId);

        var subCategoria =
            Mapper.Map<SubCategoriaViewModel,
            SubCategoria>(subCategoriaViewModel);

        subCategoria.Categoria = categoriaSelecionada;
        _subCategoriaService.Atualizar(subCategoria);

        return subCategoriaViewModel;
    }

And, there was the addition of the public Guid CategoriaId { get; set; } property in the SubCategory domain class, to serve as foreign key in the association between Category and SubCategory ( 1:N ). Here is the code:

public class SubCategoria
{
    public Guid SubCategoriaId { get; set; }
    public string SubCategoriaNome { get; set; }
    public virtual Categoria Categoria { get; set; }
    public Guid CategoriaId { get; set; }
    public ICollection<Produto> Produtos { get; set; }

    public SubCategoria()
    {
        SubCategoriaId = Guid.NewGuid();
        Produtos = new List<Produto>();
    }        
}

Who wants to take a look at the material I read about the topic, follow the links

24.02.2017 / 17:15
0

If I understand your problem well, the solution is very simple, just fill in the CategoriaId before calling the view.

Because, as you know, CategoriaId is responsible for the value of the selected object in the dropdown, if you do not initialize this variable with the correct value, the dropdown will display the default option which in your case is the first object from the Categorias list.

The solution to your problem is:

subCategoriaViewModel.CategoriaId = Id.value; 

I do not understand your structure, but it's the id of the category you saved in bd.

    
22.02.2017 / 23:17