Doubt about how to register

Asked

Viewed 79 times

3

Good afternoon guys, good I’m new here, so I apologize for anything!

My question is:

I have an equipment table, a software table and an associative equipment-software. The ratio was (Equipment) 1 N (Software) N 1 (Software), where an equipment can have several software, but that equipmentSoftware is only in that equipment, etc;

I managed to do the crud part of the equipment very good, however to register a Software in the equipment, I could only do in a separate crud.

I would like to know how to register the Equipment and a equipmentSoftware (A software in the equipment) in the same View.

I’ll post my code

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 string equNumSerie { get; set; }

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

Model software:

public partial class tblSoftware
{
  public tblSoftware()
  {
    this.tblEquipamentoSoftware = new HashSet<tblEquipamentoSoftware>();
  }
  [Key]
  public int sofIdSoftware { get; set; }
  [Display(Name = "Software")]
  [Required(ErrorMessage = "Informe o nome do Software!")]
  public string sofNome { get; set; }

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

Model Equipmentsoftware (associative):

public partial class tblEquipamentoSoftware
    {
        [Key, Column(Order = 0)]
        [Display(Name = "Equipamento")]
        public int eqsIdEquipamento { get; set; }
        [Key, Column(Order = 1)]
        [Display(Name= "Software")]
        public int eqsIdSoftware { get; set; }

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

Registering everything at once, without having to separate a piece of equipment from the Software. Please help me, and if there’s anything wrong, let me know and I’ll edit it. I’m doing c# along with the Entity framework and ADO.NET Thank you!

I want to join these two Ruds in a single form or view

Crud of the Equipment: inserir a descrição da imagem aqui

Crud of the equipmentSoftware: inserir a descrição da imagem aqui

  • 1

    Could show what crud did and a visual representation of the intended result?

  • Yes I can, I’ll put the image

  • 1

    Are you wanting that when it comes time to register an equipment, you already want to register the "Software equipment" together? Register everything at once, that’s it?

  • That’s right, I want to register you both in one form!

  • 1

    @user7845, Voce needs to make a Viewmodel where it will receive the properties of both registration you want to do, so Voce can call this model in your view and place the fields to be filled as your need

  • 1

    give a look at this link https://answall.com/questions/91021/comor-enviar-2-objectos-do-controller-para-a-view-no-c-asp-net-mvc

Show 1 more comment

1 answer

1


Well this looks a lot like an item registration in an order, I will do it in a well summarized way, but it is not the only way to do ok?

First in his controller of Equipment we will make him return a Json as follows:

Note: the get mode looks the same when you create by MVC 5 Controller with views, using Entity Framework.

Your method create POST it will be so:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(tblEquipamento tblEquipamento)
{ 
   if (ModelState.IsValid)
   {
      db.tblEquipamento.Add(tblEquipamento);
      db.SaveChanges();
   }
     return Json(new { Resultado = tblEquipamento.equIdEquipamento }, JsonRequestBehavior.AllowGet);
}

Now on in your Equipment view create you can delete the @using (Html.BeginForm()) and add the following codes:

A button to save equipment:

<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
       <a href="#" onclick="SalvarEquipamento();" class="btn btn-info">Salvar</a>
     </div>
</div>

this button will trigger a function in your Javascript that will save your device to create a Id

Just below this code you will put a div which will be "invisible" at first, but it will be there that the form will appear to register the desired software!

<div id="divSoftwares" style="display: none;"></div>

After all this procedure, you will create a file .js, in it we will put all our Javascript. I called my Equipamento.js, you can name it whatever you want, ok?

The method that will save the equipment will be this way, we will use Ajax:

function SalvarEquipamento() {

    var nip = $("#equNip").val();

    var serie = $("#equNumSerie").val();

    var token = $('input[name="__RequestVerificationToken"]').val();
    var tokenadr = $('form[action="/Equipamento/Create"] input[name="__RequestVerificationToken"]').val();

    var headers = {};
    var headersadr = {};
    headers['__RequestVerificationToken'] = token;
    headersadr['__ResquestVerificationToken'] = tokenadr;

    var url = "/Equipamento/Create";

    $.ajax({
        url: url
        , type: "POST"
        , datatype: "json"
        , headers: headersadr
        , data: {
            equIdEquipamento: 0, equNip: nip, equNumSerie: serie, __RequestVerificationToken: token
        }
        , success: function (data) {
            if (data.Resultado > 0) {
                ListarSoftwares(data.Resultado);
            }
        }
    });
}

Note: This token refers to the [ValidateAntiForgeryToken].

Still in our Equipamento.js you will make a method to list the software that is being registered with that equipment.

function ListarSoftwares(idEquipamento) {
    var url = "/EquipamentoSoftware/ListarSoftwares";
    $.ajax({
        url: url
        , type: "GET"
        , data: { id: idEquipamento}
        , datatype: "html"
        , success: function (data) {
            var divSoftwares = $("#divSoftwares");
            divSoftwares.empty();
            divSoftwares.show();
            divSoftwares.html(data);
        }
    });
}

Done this you will create a Controller for your Equipmentsoftware, you can create a controller Empty same. In it you’ll put one ActionResult who will be responsible for calling the EquipamentoSoftware, will look like this:

public ActionResult ListarSoftwares(int id)
{
   var lista = db.tblEquipamentoSoftware.Where(t => t.tblEquipamento.equIdEquipamento == id);
   ViewBag.eqsIdSoftware = new SelectList(db.tblSoftware, "sofIdSoftware", "sofNome");
   ViewBag.Equipamento = id;
   return PartialView(lista);
 }

Then you will create a view ListarSoftware, she’ll be the type List, okay?

@model IEnumerable<SistemaCadastroAtivo.Models.tblEquipamentoSoftware>

<div>
    <h4>Softwares</h4>
    <hr/>
    <div class="form-group">
        <label class="control-label col-md-2">Software</label>
        <div class="col-md-10">
            @Html.DropDownList("eqsIdSoftware", null, htmlAttributes: new { @class = "form-control", id = "Software"})
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-md-2">Tipo</label>
        <div class="col-md-10">
            <input type="text" id="Tipo" name="Tipo" placeholder="Informe L p/ Licença ou I p/ instalado" />
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <a href="#" onclick="SalvarSoftwaresEquipamento();" class="btn btn-info">Adicionar Software</a>
        </div>
    </div>
</div>

<input type="hidden" id="idEquipamento" value="@ViewBag.Equipamento" />


<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.eqsTipo)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.tblEquipamento.equNip)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.tblSoftware.sofNome)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.eqsTipo)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.tblEquipamento.equNip)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.tblSoftware.sofNome)
        </td>
        <td>
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

In it you are bringing the form of the Equipmentsoftware and also a table for the listing of the software that are being registered to this equipment.

You must have noticed a button to save the software, soon you will do the method in Equipamento.js as follows:

function SalvarSoftwaresEquipamento() {
    debugger;
    var idSoftware = $("#Software").val();
    var tipo = $("#Tipo").val();
    var idEquipamento = $("#idEquipamento").val();

    var url = "/EquipamentoSoftware/SalvarSoftwares";

    $.ajax({
        url: url
        , data: { idSoftware: idSoftware, tipo: tipo, idEquipamento: idEquipamento }
        , type: "GET"
        , datatype: "json"
        , success: function (data) {
            if (data.Resultado > 0) {
                debugger;
                ListarSoftwares(idEquipamento);
            }
        }
    })
}

And finally there in his EquipamentoSoftwareController you’ll do it:

public ActionResult SalvarSoftwares(int idEquipamento, int idSoftware, string tipo)
{
   var equipamentoSoftware = new tblEquipamentoSoftware()
   {
     tblEquipamento = db.tblEquipamento.Find(idEquipamento), 
     tblSoftware = db.tblSoftware.Find(idSoftware),
     eqsTipo = tipo
   };

    db.tblEquipamentoSoftware.Add(equipamentoSoftware);
    db.SaveChanges();   
    return Json(new { Resultado = equipamentoSoftware.eqsIdEquipamento }, JsonRequestBehavior.AllowGet);
}

Note: It is necessary that you have already done the crud software, in order to bring to the equipment view.

Your screen will look like this:

inserir a descrição da imagem aqui

When you click on save will appear the form of Equipmentsoftware:

inserir a descrição da imagem aqui

Source: https://www.youtube.com/watch?v=_z7BYLM3Lus

Browser other questions tagged

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