【问题标题】:Send Post Data to Controller with Ajax [Project .Net]使用 Ajax 将 Post 数据发送到控制器 [Project .Net]
【发布时间】:2016-06-30 21:51:36
【问题描述】:

我在 .Net 中有一个学校项目。 我尝试通过 ajax 发送一个 POST json 一个 MVC 控制器 5。我达到了控制器的正确功能,但它接收到的值为 0 或 null: values in controller are 0 or null

尽管变量已正确填充浏览器控制台: variables in browser console

你认为错在哪里?

这里有一些代码: 调用控制器的函数:

function GeneratePDF() {
    var dataToSend;
    var age = 69;    
    instruction = "trololololoCOCO";

    dataToSend = JSON.stringify({ item: { distance: age, instruction: instruction } });
   console.log("dataToSend : " + dataToSend);

    var uri = '/GeneratePDF/Print';
    $.ajax({
        type: 'POST',
        url: uri,
        data: dataToSend,
        contentType: "application/json; charset=utf-8",
    })
     .done(function (data) {
         console.log('pdf controller DONE');
     })
     .fail(function (jqXHR, textStatus, err) {
         console.log(jqXHR);
         $("#result").html(jqXHR.responseText);
     });
}

控制器:

[HttpPost]
        public ActionResult Print(test item)
        {
           //something

            return new Rotativa.ActionAsPdf("ViewPrint",new { id = item }) { FileName = "Cartographie.pdf" };
        }

型号:

public class test
    {
        public int distance;
        public string instruction;
        public test(int distance, string instruction)
        {
            this.distance = distance;
            this.instruction = instruction;
        }
    }

【问题讨论】:

    标签: c# ajax asp.net-mvc-4 asp.net-ajax


    【解决方案1】:

    不允许使用字段。

    您的模型声明必须具有 get 和 set 属性:

    public int distance { get; set; }
    public string instruction { get; set; }
    

    【讨论】:

    • @M.Vogeleer 解决您的问题后不要忘记接受/投票!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    相关资源
    最近更新 更多