c# - jquery .ajax 调用 Controller ,模型为空

标签 c# jquery ajax asp.net-mvc json

<分区>

我花了大约 10 个小时并阅读了无数帖子试图解决这个问题,但不得不承认失败,所以希望有好心人能帮我理顺。

我正在尝试将数据发送到我的 Controller (GET) 以返回部分 View 。尽管我尝试了各种变化,但 Controller 接收到的模型始终为空。为了使其真正简单,我将模型缩减为一个元素。

我错过了什么? (提前致谢)

型号:

public class TextContentViewModel
{
    public string ContentType {get; set;}
}

Controller :

public ActionResult Preview(TextContentViewModel paneContent)
{
    return PartialView("_Text");
}

Javascript:

<script type="text/javascript">

    $("#previewButton").click(showPreview);

    function showPreview() {
         content = {
            ContentType: $("#ContentTypeID").val(),
        }
                $.ajax({
                url: '@Url.Action("Preview")',
                type: 'GET',
                contentType: 'application/json',
                data: JSON.stringify(content),
                success: function (result) {
                    $('#preview').html(result);
                },
                error: function (result) {
                    alert("something went wrong");
                }
            });
         };

最佳答案

你的传入和传出变量应该有相同的名字。

尝试将您的 js 变量名称更改为

 paneContent = {
        ContentType: $("#ContentTypeID").val(),
    }

此外,不要尝试使用 GET 来发送复杂变量。那永远行不通。始终使用 POST

            type: 'POST',

关于c# - jquery .ajax 调用 Controller ,模型为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16029569/

相关文章:

c# - ASP.NET Core 2.2 集成测试 DbContext 服务未注册

c# - 类型参数 'T' 与外部类型 '...' 的类型参数同名

javascript - 带有标题的 jquery 悬停覆盖

php - jquery.post() 和 php

javascript - 用两个值计算价格

c# - C# 新手,在使用 C# 枚举和类型转换进行计算时遇到问题

c# - C# 和 C++ 中字符串操作的不同基准

javascript - 如何使用Deferred处理多个ajax请求错误?

javascript - 涉及 Webgrid 的 Ajax 帮助

javascript - 获取 Promise 的值?