Home > Mobile >  How to get data from an HTML form and send it to my controller class on .net core 6?
How to get data from an HTML form and send it to my controller class on .net core 6?

Time:12-29

I'm developing an project using .NET Core 6 that take the text from a form and send it by email to the professor previously selected and now I need to get some informations from my HTML form (specifically the text on "FeedbackTextArea" and the Professor Id) and send it to my Controller class to treat that informations but I don't have the slightest idea how to do that.

That's my View

@model FeedbackUnivicosa.Models.ViewModels.ProfessorFormViewModel;
@{
    ViewData["Title"] = "Enviar feedback";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<form>
    <fieldset>
        <legend>@ViewData["Title"]</legend>
        <div >
            <label >Curso</label>
            <select  id="cursoSelect"></select>
            <br />
            <label  mt-4>Professor</label>
            <select  id="professorSelect" asp-for="Professor.Nome" disabled=true></select>
            <br />
            <div >
                <label for="feedbackTextArea">Feedback</label>
                <textarea  id="feedbackTextArea" rows="3" placeholder="Digite Seu feedback"></textarea>
            </div>
            <br />
            <div >
                <input type="submit" value="Enviar"  />
            </div>
        </div>
    </fieldset>
</form>


@section Scripts{
    <script>
        
        $(document).ready(function () {
            $.ajax({
                type: "GET",
                datatype: "json",
                cache: false,
                url: "/Cursos/GetCursos",
                data: {},
                success: function (data) {
                    var s = '<option value="" disabled selected hidden>Selecione um Curso</option>';
                    for (var i = 0; i < data.length; i  ) {

                        s  = '<option value=" '   data[i].id   '">'   data[i].nome   '</option>';
                        console.log('id '   data[i].id   ' nome '   data[i].nome);
                    }
                    $("#cursoSelect").html(s);
                },
                error: function () {
                    alert('Error !');
                }
            });
        });

        $(function () {
            $("#cursoSelect").on("change", function () {
                var cursooId = $(this).val();
                $("#professorSelect").empty();
                $("#professorSelect").prop('disabled', false);
                var string = '<option value="" disabled selected hidden>Selecione um Professor</option>';
                $.getJSON(`/Professores/GetProfessorByCurso/${cursooId}`, (data) => {
                    $.each(data, function (i, item) {
                        string  = '<option value=" '   item.profId   '">'   item.nome   '</option>';
                        console.log(item.profId, item.nome, item.profEmail);
                    });
                    $("#professorSelect").html(string);
                    

                });
            });
        });
        
    </script>
}

And that is my Controller

using FeedbackUnivicosa.Models;
using FeedbackUnivicosa.Models.ViewModels;
using FeedbackUnivicosa.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Diagnostics;

namespace FeedbackUnivicosa.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly CursoService _cursoService;
        public HomeController(ILogger<HomeController> logger, CursoService cursoService)
        {

            _logger = logger;
            _cursoService = cursoService;
        }

        public IActionResult Index()
        {

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public IActionResult Cadastro()
        {
            return View();
        }
        public IActionResult Feedback()
        {
            ViewBag.Cursos = _cursoService.FindAll().Select(x => new SelectListItem() { Text = x.Nome, Value = x.Nome }).ToList();
            return View();
        }
        

    }
}

I'm expecting some way to send the informations to the back-end

CodePudding user response:

Not sure how is the parameter like in your action, but model binding system binds the data by name attribute.

A simple demo about how to pass the data to backend:

<form asp-action="Test">
    <fieldset>
        <legend>@ViewData["Title"]</legend>
        <div >
            <label >Curso</label>
            <select  id="cursoSelect"></select>
            <br />
            <label  mt-4>Professor</label>

                                                           //add the name attribute...
            <select  id="professorSelect" name="Nome" asp-for="Professor.Nome" disabled=true></select>
            <br />
            <div >
                <label for="feedbackTextArea">Feedback</label>

                                                                //add the name attribute...
                <textarea  id="feedbackTextArea" name="feedback" rows="3" placeholder="Digite Seu feedback"></textarea>
            </div>
            <br />
            <div >
                <input type="submit" value="Enviar"  />
            </div>
        </div>
    </fieldset>
</form>

Action:

public IActionResult Test(string Nome, string feedback)
{
    //do your stuff...
}

CodePudding user response:

add an event listner for form submit

    addEventListener('submit', (event) => {
      event.preventDefault();
      const data = JSON.stringify(Object.fromEntries(new FormData(event.target)));
      $.ajax({
        type: 'POST',
        url: 'Home/Test',
        contentType: 'application/json;charset=UTF-8',
        data: data,
        success: function (response) {
            // Do Something with response
        },
        error: function () {
          // Do Something if ajax fails
        }
      });
    });

And your controlle should be

[HttpPost]
public async Task<JsonResult> Test([FromBody] ProfessorFormViewModel modal)
{
    // Do Something in controller
}

And dont forget to add

builder.Services.AddControllers()
        .AddNewtonsoftJson(jsonOptions =>
        {
            jsonOptions.SerializerSettings.Converters.Add(new StringEnumConverter());
        });

This to your Program.cs or the value will be null

  • Related