Doubt about how to put two different things in the same view

Asked

Viewed 59 times

1

Guys, I have a small system that registers equipment and software. In data modeling a device can have several software installed on it, so the first time I made a crud to register only the equipment and then a crud to register all software from that equipment.

Good as you have noticed, I did it in crud separated.

I’d like to do it all in one crud that would be the equipment, I saw in a tutorial on how to do this, only I had some problems halfway.

I am using ADO.NET and Entityframework.

I apologize for the size of the question, but I wanted to post the whole code! My code is like this:

Model Equipamento:

public partial class tblEquipamento
    {
        public tblEquipamento()
        {
            this.tblEquipamentoSoftware = new HashSet<tblEquipamentoSoftware>();
        }
        [Key]
        public int equIdEquipamento { get; set; }
        [Required(ErrorMessage = "Informe o NIP do Equipamento")]
        [Display(Name = "NIP")]
        public string equNip { get; set; }

        public virtual ICollection<tblEquipamentoSoftware> tblEquipamentoSoftware { get; set; }
    }

Model Equipmentsoftware:

public partial class tblEquipamentoSoftware
    {
        [Key, Column(Order = 0)]
        [Display(Name = "NIP")]
        public int eqsIdEquipamento { get; set; }
        [Key, Column(Order = 1)]
        [Display(Name = "Software")]
        public int eqsIdSoftware { get; set; }
        [Required(ErrorMessage = "Informe o Tipo")]
        [Display(Name = "Tipo")]
        public string eqsTipo { get; set; }

        public virtual tblEquipamento tblEquipamento { get; set; }
        public virtual tblSoftware tblSoftware { get; set; }
    }

Sofware model:

 public partial class tblSoftware
    {
        public tblSoftware()
        {
            this.tblEquipamentoSoftware = new HashSet<tblEquipamentoSoftware>();
        }

        public int sofIdSoftware { get; set; }
        [Required(ErrorMessage = "Informe o software")]
        [Display(Name = "Nome")]
        public string sofNome { get; set; }

        public virtual ICollection<tblEquipamentoSoftware> tblEquipamentoSoftware { get; set; }

Controller Equipamento:

public ActionResult Create()
        {
           //Eu Adicionei essa parte aqui do ViewBag pq me basei em um tutorial, mas se estiver errado peço que me avisem pfvr
            ViewBag.eqsIdSoftware = new SelectList(db.tblSoftware, "sofIdSoftware", "sofNome");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "equIdEquipamento,equNip, tblEquipamentoSoftware")] tblEquipamento tblEquipamento)
        {
            if (ModelState.IsValid)
            {
                db.tblEquipamento.Add(tblEquipamento);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.eqsIdSoftware = new SelectList(db.tblSoftware, "sofIdSoftware", "sofNome", tblEquipamento.tblEquipamentoSoftware);
            return View(tblEquipamento);
        }
        public ActionResult NovoSoftwareEquipamento()
        {
            tblEquipamento equ = new tblEquipamento();
            return PartialView("_SoftwareEquipamento", new tblEquipamentoSoftware { eqsIdEquipamento = equ.equIdEquipamento});
        }

Well I created two EquipamentoSoftware in the crud of Equipamento

View Equipment:

@using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>tblEquipamento</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group col-lg-4">
                        @Html.LabelFor(model => model.equNip, htmlAttributes: new { @class = "control-label col-md-2" })
                        <div class="col-lg-9">
                            @Html.EditorFor(model => model.equNip, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.equNip, "", new { @class = "text-danger" })
                        </div>
                    </div>

            @Html.Partial("_Softwares")

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Cadastrar" class="btn btn-success" />
                </div>
            </div>
        </div>
    }

Agr a Partial I created:

_Software:

@model IEnumerable<TesteCadastroAtivo.Models.tblEquipamentoSoftware>

<div class="actions">
    <button type="button" class="btn btn-default btn-sm" id="adicionar-novo-software">
        Adicionar Software
    </button>
</div>

<div id="area-software">
    @if (Model != null)
    {
        foreach (var software in Model)
        {
            @Html.Partial("_SoftwareEquipamento", software);
        }
    }
</div>

<script src="~/Scripts/jquery-1.8.0.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $("#adicionar-novo-software").click(function () {
            $.get('/Equipamento/NovoSoftwareEquipamento', function (template) {
                $("#area-software").append(template);
            });
        });
    });
</script>

_Softwareequipment:

@model TesteCadastroAtivo.Models.tblEquipamentoSoftware

@using (Html.BeginCollectionItem("tblEquipamentoSoftware"))
{
    <div class="form-group">
        @Html.HiddenFor(model => model.eqsIdEquipamento)
        @Html.HiddenFor(model => model.eqsIdSoftware)

        <div class="form-group">
            @Html.LabelFor(model => model.eqsTipo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.eqsTipo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.eqsTipo, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="col-md-1">
            <a class="btn red" onclick="$(this).parent().parent().remove();">Excluir</a>
        </div>
    </div>
}

People if I leave the code so far I can make appear on the screen of Equipment for the user to put the type of software, however I want to put also for the user to select the Software, only when I put this part in my _SoftwareEquipamento he makes a mistake

 <div class="form-group">
            @Html.LabelFor(model => model.eqsIdSoftware, "eqsIdSoftware", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("eqsIdSoftware", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.eqsIdSoftware, "", new { @class = "text-danger" })
            </div>
        </div>

Error generated:

Additional information: The Viewdata item that has the key 'eqsIdSoftware' is of type 'System.Int32' but must be of type 'Ienumerable'.

Someone could help me, sorry anything, I’m still learning!!!

  • 1

    As the error indicates, you are using a key to fetch an element and use the element as if it were Ienumerable, but it is a System.Int32 in your model.

  • 1

    And how can I let the user select the software?]

  • 1

    eqsIdSoftware is the right software table key?

  • 1

    @Mauroalmeida yes, right!

1 answer

3


Example source

Customerdisplayviewmodel.Cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace BlipDrop.ViewModels
{
    public class CustomerEditViewModel
    {
        [Display(Name = "Customer Number")]
        public string CustomerID { get; set; }

        [Required]
        [Display(Name = "Customer Name")]
        [StringLength(75)]
        public string CustomerName { get; set; }

        [Required]
        [Display(Name = "Country")]
        public string SelectedCountryIso3 { get; set; }
        public IEnumerable<SelectListItem> Countries { get; set; }

        [Required]
        [Display(Name = "State / Region")]
        public string SelectedRegionCode { get; set; }
        public IEnumerable<SelectListItem> Regions { get; set; }
    }
}

Create.cshtml, Country snippet

...
<div class="form-group">
    @Html.LabelFor(x => Model.SelectedCountryIso3, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-5">
        @Html.DropDownListFor(x => Model.SelectedCountryIso3, new SelectList(Model.Countries, "Value", "Text"), htmlAttributes: new { @class = "form-control", id = "Country"})
        @Html.ValidationMessageFor(x => x.SelectedCountryIso3, "", new { @class = "text-danger" })
    </div>
</div>
...

Countriesrepository.Cs

using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;

namespace BlipDrop.Data
{
    public class CountriesRepository
    {
        public IEnumerable<SelectListItem> GetCountries()
        {
            using (var context = new ApplicationDbContext())
            {
                List<SelectListItem> countries = context.Countries.AsNoTracking()
                    .OrderBy(n => n.CountryNameEnglish)
                        .Select(n =>
                        new SelectListItem
                        {
                            Value = n.Iso3.ToString(),
                            Text = n.CountryNameEnglish
                        }).ToList();
                var countrytip = new SelectListItem()
                {
                    Value = null,
                    Text = "--- select country ---"
                };
                countries.Insert(0, countrytip);
                return new SelectList(countries, "Value", "Text");
            }
        }
    }
}

Just follow suit and move on to your goal. This example shows a list of countries in a Drowpdownlist.

  • @Rafael, if you thought the answer helped you solve your problem, put it as an accepted answer.

Browser other questions tagged

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