ASP.NET.MVC Basic doubt - Registration with "subform"?

Asked

Viewed 196 times

2

I’m working on my first ASP.MVC project with C# and I’m playing with student registration. On the student registration page there is a Checkbox that when marked (I imagined) should enable the addition of allergies that the student may have. See the bank (very basic): inserir a descrição da imagem aqui

In a Windowsform I would have an allergy subform associated with the student form, for the user to select as many allergies as he wanted on a grid or listbox. How to solve this in web development? I’m confused, because the view is associated with a model, in the student case. Your Ubmit button records in the Students table... Then how, on the student registration page, list the items in the table Allergies for the user to select the ones you want. And then how to register in the Allergy table when submitting the Student page?


Update-01:

I now have this model:

public partial class Pessoa
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Pessoa()
    {
        this.AlergiasPessoas = new HashSet<AlergiasPessoas>();
    }

    public int ID { get; set; }
    public string nome { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<AlergiasPessoas> AlergiasPessoas { get; set; }
}

Este Controller:

// POST: Pessoas/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ID,nome")] Pessoa pessoa)
    {
        if (ModelState.IsValid)
        {
            db.Pessoa.Add(pessoa);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(pessoa);
    }

    // GET: Pessoas/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Pessoa pessoa = db.Pessoa.Find(id);
        if (pessoa == null)
        {
            return HttpNotFound();
        }
        return View(pessoa);
    }

And is View: inserir a descrição da imagem aqui

I customized it with this listbox:

<!-- Item adicionado para permitir selecionar Alergias-->
    @{ CadastroAluno.Models.TESTEEntities Banco = new CadastroAluno.Models.TESTEEntities(); }
    <div class="form-group">
        <label class="control-label col-md-2" for="ID">Possui Alergia?</label>
        <div class="col-md-10">
            <input type="checkbox" onclick="ExibeItem(this.checked)" htmlAttributes="{ class = form-control }" />
        </div>
    </div>

    <div class="form-group" id="Oculta" style="display:none"> 
        @Html.LabelFor(model => model.AlergiasPessoas, "AlergiasPessoas", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">

            @Html.ListBoxFor(model => model.AlergiasPessoas, new SelectList(Banco.AlergiasPessoas, "ID", "ID_Alergia"),
                      htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.AlergiasPessoas, "", new { @class = "text-danger" })
        </div>
    </div>
    <!-- - -->

and with this java:

<script type="text/javascript">
function ExibeItem(CheckBox) {
    if (CheckBox == false) {            
        document.getElementById('Oculta').style.display = 'none';
    } else {
        document.getElementById('Oculta').style.display = 'block';
    }
}

but Listbox remains empty... How to fill it with items registered in the Allergy table?

1 answer

2


A method to solve this problem is:

In the View, inside the form, creates a div which contains all elements of allergy, and assigns a css to control when she should appear or not, this css can be a visibility: hidden, or a display:none.

And you control the click on the checkbox through a jquery. So when the checkbox is marked you make this div containing allergy information appear.

Regarding the data sent from View to the Controller,by clicking the send button, Voce makes the Model concerning this View pass the values that will be treated directly on Controller

EDITED:

In the same way that Voce is passing view information to controller, it has how to pass controller information to view see here. So Voce can take the allergy list to the view and, as far as I can see, is using Razor, so Voce can make a list of checkboxes with existing allergies, see how here. I think from now on you can do it, since you already know how to pass information from view to controller. If you still have any doubts just comment and/or modify the question.

  • Thank you @Um ! Your reply gave me a north. But as I said I’m new at this thing of views... If you can go easy on me... Good using the magic of Entityframework Databasefirst Visual Studio created the 3 table templates for me (I just had to add an Allergy Id). Then Scaffold created for me the Controller and the Views of the Pessoa table/template. I then took View Create as an example. I will edit the post and add this new part, ok?

Browser other questions tagged

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