Partialview relationships Asp.net mvc 5

Asked

Viewed 458 times

1

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

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

I’ve been two days on this assignment!!

Could someone help me to assemble the logic of the record? I mean, including the 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>

}

1 answer

1


I found some errors in your code:

  1. Inside the foreach of Partialview, the object item is the type Model2 and this type does not contain a property called MeuOutroEnum, I believe you’re trying to use the property of Model2 which is of that kind, namely the property Tipo (the same way you did in the DropDownListFor;
  2. In the DropDownListFor, there is also an error in the second parameter when creating a new SelectList with only one parameter, this parameter must 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 existing Enums of Meuoutroenum you can use the following methods to transform your Enum into a Ienumerable:

    Enum.Getvalues(typeof(Meuoutroenum)). Cast())

What I managed to run here without errors was (without considering the 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>
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.