c# - Controller 收不到来自json的数据

标签 c# asp.net-mvc partial-views

我正在开发管理页面,但无法从 json 接收数据。 我有一个创建 View ,在其中我创建了一个脚本来在选择某种类型时显示我的局部 View 。但是当我选择酒店类型时,我的 Controller 没有接收到数据。当我选择其他类型时,效果很好。 谁能告诉我问题出在哪里?

我的代码:

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);
        }

(模型)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; }
    }
}

问题:

enter image description here

enter image description here

最佳答案

您的 ajax 请求指定了 typeurldataType 和一个回调 success 函数,但它从未真正发送任何带有它的表单数据(如果您不使用表单将数据提交到服务器,则不知道为什么这些字段以任何方式出现在表单中 - 但这是与您发布的问题不同的问题。

要解决您的问题,您应该将您的 ajax 请求更改为 POST 而不是 GET 并包含您的模型数据,如下所示:

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);
    }
})

关于c# - Controller 收不到来自json的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65050536/

相关文章:

asp.net-mvc - 如何同时使用内部表单例份验证和 Azure AD 身份验证

c# - 如何在没有打开/保存对话框的情况下播放 Telerik RadCaptcha .wav 文件

ruby-on-rails - Rails 渲染助手不渲染

c# - SoapCoreOptions.Binding 现已过时

c# - 将数字字符串转换为四舍五入的小数 (C#)

c# - 普遍使用 Int64 而不是 int 的缺点 (C#)

javascript - 如何在asp.net和vb.net中单击删除按钮后向后重定向两步

局部渲染后未执行局部中的 Javascript block ——Rails 3

asp.net - 使用 Razor View Engine 将内容从部分 View ASP.NET MVC 3 注入(inject)特定部分

c# - 在 C# 2.0 中使用 Invoke 调用时,参数从 null 转换为 DateTime.MinValue