PartialView relationships asp.net mvc 5

1

I'm having trouble creating the logging logic of models that has relationships between them. One exists only the reference, but in the other, the reference is of the List < > type.

I created a partialview containing only the field, but I can not get the screen to be displayed to register. Several errors have already been shown: nullreferenceexception, the model is 'x' but waits for type 'y', etc.

I'm already two days into this task !!

Can someone help me with the registration logic? I mean, including views and partials views

Model 1

    public Guid Id { get; set; }
    [Display(Name = "Nome")]
    public string Nome { get; set; }
    [Display(Name = "Campo2")]
    public string Campo2 { get; set; }
    [Display(Name = "MeuEnum")]
    public MeuEnum MeuEnum { get; set; }
    public IList<Model2> Model2 { get; set; } = new List<Model2>();

Model 2

    public Guid Id { get; set; }

    [Display(Name = "MeuOutroEnum")]
    public MeuOutroEnum Tipo { get; set; }
    public virtual Model1 Model1 { get; set; }

My view Create

//Os campos do model1....

@Html.Partial("_PartialModel2", Model.Model2)

My partial view

@model List<MeuProjeto.Presentation.Web.Modelos.Model2>

@foreach (var item in Model)
{
  <div class="form-group">
  @Html.LabelFor(model => item.MeuOutroEnum, htmlAttributes: new { @class = "control-label col-md-2" })
  <div class="col-md-10">
    @Html.DropDownListFor(model => item.Tipo, new SelectList(Model[0].Tipo))
    @Html.ValidationMessageFor(model => item.Tipo, "", new { @class = "text-danger" })
  </div>

}

    
asked by anonymous 09.11.2017 / 15:27

1 answer

1

I found some errors in your code:

  • Within the foreach of PartialView, the item object is of type Model2 and this type does not contain a property called MeuOutroEnum , I believe you are trying to use the Model2 property that is of that type, , the Tipo property (in the same way as you did in DropDownListFor ;
  • In DropDownListFor , there is also an error in the second parameter, when creating a new SelectList with only one parameter, this parameter should implement the interface IEnumerable and Model[0].Tipo is an Enum that does not implement. If the idea is to create a DropDown with all the existing Enums of MyOutroEnum you can use the following methods to turn your Enum into an IEnumerable:

    Enum.GetValues (typeof (MeuOutroEnum)) Cast ())

  • What I was able to execute here without errors was (without considering CSS):

    @foreach (var item in Model)
    {
        <div class="form-group">
            @Html.LabelFor(model => item.Tipo)
            <div class="col-md-10">
                @Html.DropDownListFor(model => item.Tipo,
                    new SelectList(Enum.GetValues(typeof(MeuOutroEnum)).Cast<MeuOutroEnum>()))
                @Html.ValidationMessageFor(model => item.Tipo,"")
            </div>
        </div>
    }
    
        
    11.11.2017 / 14:54