How to get the values of the view to the MVC controller - RAZOR

0

I currently have this code in a view, and I want to get all the values to pass them to the controller and create them in the database

I have 2 models Subjects:

namespace CalculaNotas.Models
public class Materias
{

    public int materiasId { get; set; }

    [Required]
    [MinLength(length: 5, ErrorMessage = "El nombre debe contener al menos 5 caracteres")]
    [MaxLength(length: 20, ErrorMessage = "El nombre debe contener maximo 2 caracteres")]
    [Index(IsUnique = true)]
    public string nombre { get; set; }

    public virtual List<Calificaciones> calificaciones { get; set; }

}

Qualifications:

public class Calificaciones
{

    const double MIN_VALUE = 0.0;
    const double MAX_VALUE = 5.0;

    public int Id { get; set; }

    [Required]
    public int materiasId { get; set; }
    public virtual Materias materia { get; set; }

    [Required]
    [Display(Name = "Nota 1")]
    [Range(minimum: MIN_VALUE, maximum: MAX_VALUE, ErrorMessage = "Debe ingresar un numero entre 0.0  y 5.0")]
    public Double nota1 { get; set; }

    [Required]
    [Display(Name = "Nota 2")]
    [Range(minimum: MIN_VALUE, maximum: MAX_VALUE, ErrorMessage = "Debe ingresar un numero entre 0.0  y 5.0")]
    public Double nota2 { get; set; }

    [Required]
    [Display(Name = "Nota 3")]
    [Range(minimum: MIN_VALUE, maximum: MAX_VALUE, ErrorMessage = "Debe ingresar un numero entre 0.0  y 5.0")]
    public Double nota3 { get; set; }

    [Display(Name = "Resultado")]
    public Double resultado { get; set; }


}

And this is the code that I have the view to dynamically show me the materials stored in the bd and create the fields for the grades

 @model  CalculaNotas.Models.Calificaciones
@{
ViewBag.Title = "Create";
}

<h2>Create</h2>


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

<div class="form-horizontal">
    <h4>Calificaciones</h4>

    <table class="table table-bordered">
        <tr >
            <th class="col-md-1"> @Html.DisplayNameFor(model => model.materia) </th>
            <th class="col-md-1" style="text-align:center">@Html.DisplayNameFor(model => model.nota1)</th>
            <th class="col-md-1" style="text-align:center">@Html.DisplayNameFor(model => model.nota2)</th>
            <th class="col-md-1" style="text-align:center">@Html.DisplayNameFor(model => model.nota3)</th>
        </tr>

        @foreach (var materia in (IEnumerable<CalculaNotas.Models.Materias>)ViewBag.materias)
        {
            <tr >
                <td class="col-md-1">@Html.DisplayFor(model => materia.nombre)</td>
                <td class="col-md-1">
                    @Html.EditorFor(model => model.nota1, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.nota1, "", new { @class = "text-danger" })
                </td>
                <td class="col-md-1">
                    @Html.EditorFor(model => model.nota2, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.nota2, "", new { @class = "text-danger" })
                </td>
                <td class="col-md-1">
                    @Html.EditorFor(model => model.nota3, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.nota3, "", new { @class = "text-danger" })
                </td>

The code of the contolador is the following

   // GET: Calificaciones/Create
    public ActionResult Create()
    {
        var materias = db.Materias.ToList();
        ViewBag.materias = materias;
        return View();
    }

    // POST: Calificaciones/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,materiasId,nota1,nota2,nota3,resultado")] Calificaciones calificaciones)
    {
        if (ModelState.IsValid)
        {
            db.Calificaciones.Add(calificaciones);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.materiasId = new SelectList(db.Materias, "materiasId", "nombre", calificaciones.materiasId);
        return View(calificaciones);
    }

What I want to do is pass the id of the subjects and the grades that I enter in the fields to the controller and then store them in the database

    
asked by kcrad100 17.03.2017 в 04:43
source

2 answers

1

Since you say you're starting. I suggest this solution to make a better idea. In this example, I assume that there are no properties for "nota1, nota2, nota3" in the model and that's why I do not use it, besides I think it's coherent not to have those properties because they could vary in number.

To solve it, I would do it like this:

1. Create a new Controller called for example "Notes":

public class NotasController : Controller
    {
        // GET: Notas
        [HttpGet]
        public ActionResult Notas()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Notas(int nota1, int nota2, int nota3)
        {
            return View();	
        }

    }
}

2. Create a new empty view for that action. The Post method would be in charge of receiving the data from the view.

So I would add the parameters that I expect to receive from the view and that corresponds to the Id of the text fields, the notes.

In the view, you would create a form.

Since the ActionResult and the view have the same name, it will automatically search for it.

Note that the IDs of the text fields correspond to the parameters of the ActionResult method "Notes".

As you may notice, the values written in the form (BeginForm) in the view are sent when you click on the send button and received in the controller as shown in the local variables window.

At that point you can already make the insertion in the bd.

Hopefully this example will guide you.

    
answered by 17.03.2017 в 07:24
0

in the controller you should receive an arrangement of qualifications, not just an object

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Calificaciones[] calificaciones)
{
    if (ModelState.IsValid)
    {
        db.Calificaciones.Add(calificaciones);
        db.SaveChanges();
        return RedirectToAction("Index");
    }


}
    
answered by 21.03.2017 в 04:39