Warm tip: This article is reproduced from serverfault.com, please click

The controller does not receive data from json

发布于 2020-11-28 14:15:08

I'm developing an administration page and I'm having trouble receiving my data from json. I have a Create view and inside it I created a script to show my partial views when selecting a certain type. But when I select the Hotel type, my controller is not receiving the data. When I select the other types, it works well. Can anyone tell me what the problem is?

My Code:

Create.cshtml

@model ProjetoFinal.Models.Item

@{
    ViewBag.Title = "";
}


<h2>@Resource.Criar</h2>


<a href="@Url.Action("ChangeLanguage_Create", "Trans", new { lang = "pt" })">Português</a> |
<a href="@Url.Action("ChangeLanguage_Create", "Trans", new { lang = "en" })">Inglês</a>
<br />


@using (Html.BeginForm("Create", "Trans", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        <hr />
        <div class="form-group">
            @Html.LabelFor(model => model.Titulo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Titulo, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Titulo, "", new { @class = "text-danger" })
            </div>
        </div>

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

        <div class="form-group">
            @Html.LabelFor(model => model.Main_Image, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="col-md-10">
                    <input type="file" name="imagem_principal" id="createimageinput" />
                    @Html.ValidationMessageFor(model => model.Main_Image, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>


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

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

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Tipo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <!--Ao escolher o tipo vai aparecer os campos respetivos dessa categoria
                atraves da funcao ddldropdown-->
                @Html.DropDownListFor(model => model.Tipo, new SelectList(Model.tipos, "ID", "Tipo"), Resource.Selecionar_Tipo, htmlAttributes: new { @id = "ddldropdown", @class = "form-control" })
            </div>
        </div>

        <div id="partialDiv">

        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" id="btnsave" value="@Resource.Criar" class="btn btn-default" />
            </div>
        </div>

    </div>


    @section Scripts
    {
        <!--Script to add Views from the Others folder in the "partialDiv"-->
        <script type="text/javascript">

            $("#ddldropdown").change(function () {
                var txt = $("#ddldropdown option:selected").text();

                if (txt == null || txt == "Selecionar Tipo")
                    $('#partialDiv').html('');

                else if (txt == "Teatro" || txt == "Feira" || txt == "Exposição" || txt == "Hotel" || txt == "Cinema" || txt == "Musica") {
                    $.ajax({
                        type: 'get',
                        url: '/Outros/Create_' + txt,
                        dataType: 'html',
                        success: function (html) {
                            $('#partialDiv').html(html);
                        }
                    });
                }
                else if (txt == "Parques/Percursos Pedestres") {
                    $.ajax({
                        type: 'get',
                        url: '/Outros/Create_Percurso',
                        dataType: 'html',
                        success: function (html) {
                            $('#partialDiv').html(html);
                        }
                    });
                }
                else {
                    $.ajax({
                        type: 'get',
                        url: '/Outros/Create_Other',
                        dataType: 'html',
                        success: function (html) {
                            $('#partialDiv').html(html);
                        }
                    });
                }
            });


        </script>

        <!--Script to submit partialDiv data-->
        <script type="text/javascript">

            window.jQuery(document).ready(function () {
                $('#btnsave').click(function () {
                    var txt = $("#ddldropdown option:selected").text();
                    var frm = $("form");
                    var data = new FormData($("form")[0]);
                    if (txt == "Teatro" || txt == "Feira" || txt == "Exposição" || txt == "Hotel" || txt == "Cinema" || txt == "Musica") {

                        var files = $("#createimageinput").get(0).files;

                        // Add the uploaded file to the form data collection
                        if (files.length > 0) {
                            for (f = 0; f < files.length; f++) {
                                data.append("imgfile", files[f]);
                            }
                        }

                        $.ajax({
                            url: '/Outros/Create_' + txt,
                            method: "POST",
                            processData: false,
                            data: data,
                            dataType: 'html',
                            contentType: false,
                        });

                    }
                    else if (txt == "Parques/Percursos Pedestres")
                    {
                            $.ajax({
                        url: '/Outros/Create_Percurso',
                                method: "POST",
                                processData: false,
                                data: data,
                                dataType: 'html',
                                contentType: false,
                            });
                    }
                    else
                    {
                        if (txt != null || txt != "Selecionar Tipo")
                        {
                                $.ajax({
                            url: '/Outros/Create_Other',
                                    method: "POST",
                                    processData: false,
                                    data: data,
                                    dataType: 'html',
                                    contentType: false,
                                });
                        }
                    }

                    });
                });
        </script>

<!--Script to place the Autocomplete at the Address-->
<script>
                // This example requires the Places library. Include the libraries=places
                // parameter when you first load the API. For example:
                // <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCvSxmjQNuUVyhYFJ8SmXHa0sQKgpiLBLA&libraries=places">

                            function initMap() {
                                google.maps.event.addDomListener(window, 'load', function () {
                                    var options = {
                                        types: ['geocode'],
                                        componentRestrictions: { country: "pt" }
                                    };

                                    var input = document.getElementById('Endereco');
                                    var autocomplete = new google.maps.places.Autocomplete(input, options);

                                    google.maps.event.addListener(autocomplete, 'place_changed', function () {
                                        var near_place = autocomplete.getPlace();
                                        document.getElementById('Latitude').value = near_place.geometry.location.lat();
                                        document.getElementById('Longitude').value = near_place.geometry.location.lng();
                                    });
                                });
                }
                $("#Endereco").change(function () {
                                document.getElementById('Latitude').value = '';
                    document.getElementById('Longitude').value = '';
                });
</script>

<!--Google API-->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCvSxmjQNuUVyhYFJ8SmXHa0sQKgpiLBLA&libraries=places&callback=initMap"
        async defer></script>

<script type="text/javascript">
                $('#btnsave').click(function () {
                    var form = $("#formH");
                    var url = form.attr("action");
                    var formData = form.serialize();
                    $.post(url, formData, function (data) {
                                $("#msg").html(data);
                    });
                })
</script>
    }

<div>
    @Html.ActionLink(Resource.Voltar, "Index")
</div>
}

Create_Hotel.cshtml

@model ProjetoFinal.Models.Hotel

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

@using (Html.BeginForm("Create_Hotel", "Outros", FormMethod.Post))
{
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Outras_Imagens, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="col-md-10">
                    <input type="file" name="images" multiple="multiple" id="imagens"/>
                    @Html.ValidationMessageFor(model => model.Outras_Imagens, "", new { @class = "text-danger" })
                </div>
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Preco, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Preco, new { htmlAttributes = new { @type = "number", @min = "0", @step = "0.01", @value = "0", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Preco, "", new { @class = "text-danger" })
            </div>
        </div>

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

        <div class="form-group" id="div_comodidades">
            @Html.LabelFor(model => model.Comodidades, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10" id="divCom">
                <div class="input-group">
                    <span class="input-group-btn">
                        @Html.EditorFor(model => model.Comodidades, new { htmlAttributes = new { @id = "comodidades", @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Comodidades, "", new { @class = "text-danger" })
                        <input type="button" class="btn btn-primary" id="com" value="+" onclick="addComodidades()" />
                    </span>
                </div>
            </div>
        </div>

        <div class="form-group" id="div_condicoes">
            @Html.LabelFor(model => model.Condicoes, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10" id="divCon">
                <div class="input-group">
                    <span class="input-group-btn">
                        @Html.EditorFor(model => model.Condicoes, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Condicoes, "", new { @class = "text-danger" })
                        <input type="button" class="btn btn-primary" value="+" onclick="addCondicoes()" />
                    </span>
                </div>
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Telefone1, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Telefone1, new { htmlAttributes = new { @type = "number", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Telefone1, "", new { @class = "text-danger" })
            </div>
        </div>

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.Avaliacao, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Avaliacao, new { htmlAttributes = new { @type = "number", @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Avaliacao, "", new { @class = "text-danger" })
            </div>
        </div>
    </div>
    @section Scripts
    {
        <script type="text/javascript">
            var cont = 0;
            var cont1 = 0;
            //function to add more fields for the user to enter more comodidades
            function addComodidades() {
                cont++;
                $("#div_comodidades").append(`<div class="col-md-10" id="campo` + cont + `" style="margin-left:16.7%">
                                                    <div class="input-group">
                                                        <span class="input-group-btn">
                                                            <input class="form-control text-box single-line"  name="Comodidades" placeholder="Comodidades" type="text" value="" id="input_comodidades` + cont + `"/>
                                                            <span class="field-validation-valid text-danger" data-valmsg-for="Comodidades" data-valmsg-replace="true"></span>
                                                            <input type="button"  id="` + cont + `" class="btn btn-primary" value="-"  style="padding-left:15px;"/>
                                                        </span>
                                                    </div>
                                  </div>`);
            }

            //function to add more fields for the user to enter more condicoes
            function addCondicoes() {
                cont1++;
                $('#div_condicoes').append(`<div class="col-md-10" id="campo1` + cont1 + `" style="margin-left:16.7%">
                                                    <div class="input-group">

                                                        <span class="input-group-btn">
                                                            <input class="form-control text-box single-line" name="Condicoes" placeholder="Condicoes" type="text" value="" id="input_condicoes` + cont1 + `" />
                                                            <span class="field-validation-valid text-danger" data-valmsg-for="Condicoes" data-valmsg-replace="true"></span>
                                                              <input type="button"  id="` + cont1 + `" class="btn btn-primary" value="-" style="padding-left:15px;"/>
                                                        </span>
                                                    </div>
                                                </div>`);
            }

            //function to remove the comodidades field that the user added
            $('#div_comodidades').on('click', '.btn-primary', function () {
                var button_id = $(this).attr("id");
                $('#campo' + button_id + '').remove();

            });

            //function to remove the condicoes field that the user added
            $('#div_condicoes').on('click', '.btn-primary', function () {
                var button_id = $(this).attr("id");
                $('#campo1' + button_id + '').remove();

            });


        </script>
    }
}

@{

    Layout = null;

}

TransController.cs

public class TransController : Controller
{
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(FormCollection formCollection)
        {
            Item item = new Item();
            //add the database
        }
}

OutrosController.cs

public class OutrosController : Controller
{
        [HttpGet]
        public ActionResult Create_Hotel()
        {
            Hotel hotel = new Hotel();
            return View(hotel);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create_Hotel(Hotel hotel, HttpPostedFileBase[] images)
        {

            //add the database
            return View(hotel);
        }

}

(Model) Hotel.cs

public class Hotel
{
    public int ID { get; set; }

    public String Preco { get; set; }

    public String Comodidades { get; set; }

    public List<String> array_comodidades { get; set; } 

    public String Condicoes { get; set; }

    public List<String> array_condicoes{ get; set; }

    [Display(Name = "Telefone")]
    public int? Telefone1 { get; set; }

    [Display(Name = "Telemovel/Fax")]
    public int? Telefone2 { get; set; }

    public String Email { get; set; }

    public String Tipo_Hotel { get; set; }

    [Range(0, 5)]
    public String Avaliacao { get; set; }

    public List<Imagem> Imagens { get; set; }

    [Display(Name = "Imagens_Secundárias", ResourceType = typeof(Resource))]
    public String Outras_Imagens { get; set; }

    public class TransmontanosDBContext : DbContext
    {
        public DbSet<Hotel> Transmontanos { get; set; }
    }
}

Problem:

enter image description here

enter image description here

Questioner
Laura Saraiva
Viewed
0
21k 2020-11-28 23:16:08

Your ajax request specifies type, url, dataType and a callback success function but it never actually sends any of the form data with it (not sure why these fields are in a form any way if youre not using the form to submit the data to the server- but that's a different problem than your posting about.

To fix your issue, you should change your ajax request to a POST instead of GET and include your model data with it as follows:

var model = { Id = $("#Id").val(),
              Preco = $("#Preco").val(),
              //populate the rest of your fields here just like Id
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: '/Outros/Create_Percurso',
    contentType: "application/json",
    success: function (html) {
        $('#partialDiv').html(html);
    }
})