简体   繁体   中英

Send Post Data to Controller with Ajax [Project .Net]

I have a project in .Net for school. I try to send a POST json through ajax a MVC controller 5. I reached the correct function of the controller but it received values are 0 or null: values in controller are 0 or null

Despite that variables are properly filled the browser console: variables in browser console

Where does the fault do you think?

Here are some code : Function that call controller :

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

Controller :

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

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

Model :

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

Fields are not allowed.

Your model declaration must have get and set properties:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM