0

It has been 3 days am trying to sending the [POST] form data using ajax, Javascript & HTML into MVC controller but getting null.

Please find the controller and ajax code please help me on this also let me know is it possible or not to send the data from ajax to mvc controller?

I am beginner .....thanks in advance.

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> CreateNewBug([FromBody] BugTrackerRequest bugTrackerRequest)
{
    // BugTrackerResponse bugTrackerResponse = null;
    if (ModelState.IsValid)
    {
        var Request = await _projectDetails.CreateNewBug(bugTrackerRequest);

        if (Request > 0)
        {
            BugTrackerResponse bugTrackerResponse = new BugTrackerResponse();
            bugTrackerResponse.Issuccess = true;
            // return Ok(new {Messgage="Data save successfully in the DB"});     
            return Ok();
        }
    }
    return StatusCode(500, new { Message = "Something went wrong" });
    // return bugTrackerResponse;
    //return StatusCode();

}

public class BugTrackerRequest:APIResponse
    {
        public int TicketId { get; set; }
        public string ProjectName { get; set; }
        public string ProjectDescription { get; set; }
        public string Title { get; set; }
        public string Status { get; set; }
        public string AssignTo { get; set; }
        public string AssignFrom { get; set; }
        public byte[] Attachment { get; set; }
        public string Impact { get; set; }
        public string Platform { get; set; }
        public string Priority { get; set; }
        public string BugType { get; set; }
        public DateTime CreatedDate { get; set; }
    }
}

function savedetails() {
 let saveuidetails = new   BugdetailRequestclass();

 saveuidetails.ProjectName = $('#projectprojectname').val();
    saveuidetails.ProjectDescription = $('#description').val();
    saveuidetails.Title = $('#title').val();
    saveuidetails.Status = $('#status').val();
    saveuidetails.AssignTo = $('#assignto').val();
    saveuidetails.AssignFrom = $('#assignfrom').val();
    saveuidetails.Attachment = $('#Attfileupload').val;
    saveuidetails.Impact = $('#Priority').val();
    saveuidetails.Platform = $('#platform').val();
    saveuidetails.Priority = $('#Priority').val();
    saveuidetails.BugType = $('bugtype').val();
    saveuidetails.CreatedDate = $('#currentdate').val();

 $.ajax({
        type: 'POST',
        url: '/TicketController1/CreateNewBugFromBody',
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify(saveuidetails),
        success: function (data) {
            console.log('success', data);
        },
        error: function () { alert('Exeption:'); }
    });
 }
Alex K.
  • 171,639
  • 30
  • 264
  • 288
dks
  • 45
  • 6

2 Answers2

1

Your URL in POST is wrong, please change

/TicketController1/CreateNewBugFromBody

to

 /TicketController1/CreateNewBug

Please verify that your controller class is named TicketController1.

To start with, please comment out

saveuidetails.Attachment = $('#Attfileupload').val;

in js and

public DateTime CreatedDate { get; set; }
public byte[] Attachment { get; set; }

When controller method is working, you may look at the Attachment which will be a challenge. You basically have three choices (https://stackoverflow.com/a/4083908/14072498):

  1. Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
  2. Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re- associates the file and the metadata.
  3. Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.

Else, your code shown here looks OK to me, and there is no problem using a MVC controller for this. If controller contains API methods only, you should extend from ControllerBase instead of Controller, and annotate controller with [ApiController]. The latter invokes model validation automatically.

When implementing new API end-points, always start with something simple and verify with e.g. Postman that you can reach your new end-point.

Roar S.
  • 8,103
  • 1
  • 15
  • 37
0
url: '/TicketController1/CreateNewBugFromBody',

public async Task<IActionResult> CreateNewBug([FromBody] BugTrackerRequest bugTrackerRequest)

First, check your request URL and the action method, it seems that you are submitting the form to the CreateNewBugFromBody method, instead of CreateNewBug action method. So try to change your code as below (I assume your controller name is TicketController1 and you want to submit to the CreateNewBug method):

 $.ajax({
        type: 'POST',
        url: '/TicketController1/CreateNewBug',
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify(saveuidetails),
        success: function (data) {
            console.log('success', data);
        },
        error: function () { alert('Exeption:'); }
    });

Second, please check your JQuery object BugdetailRequestclass, in the action method, it receives a BugTrackerRequest object. So, try to modify your code as below (please change the request url and the jquery selector value to yours):

function savedetails() {
    var saveuidetails = {};  //define a object
    saveuidetails.ProjectName = $('#ProjectName').val();
    saveuidetails.ProjectDescription = $('#Description').val();
    saveuidetails.Title = $('#Title').val();
    saveuidetails.Status = $('#Status').val();
    saveuidetails.AssignTo = $('#AssignTo').val();
    saveuidetails.AssignFrom = $('#AssignFrom').val();
    saveuidetails.Attachment = $('#Attfileupload').val;
    saveuidetails.Impact = $('#Priority').val();
    saveuidetails.Platform = $('#Platform').val();
    saveuidetails.Priority = $('#Priority').val();
    saveuidetails.BugType = $('#BugType').val();  
    saveuidetails.CreatedDate = $('#CreatedDate').val();

    $.ajax({
        type: 'POST',
        url: '/Home/CreateNewBug',
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify(saveuidetails),
        success: function (data) {
            console.log('success', data);
        },
        error: function () { alert('Exeption:'); }
    });
}

Besides, you could add a breakpoint in the JavaScript resource and CreateNewBug action method, and check whether you could get the correct data before/after send Ajax request. Screenshot as below:

JavaScript debug screenshot (using F12 developer tools)

enter image description here

Action method debug screenshot:

enter image description here

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30
  • Thank you so much @Zhi Lv now it is working fine after the changes you told me to do ... also can you pls help me ,how should i improve code logic thru self pratice . – dks Dec 21 '20 at 11:48
  • @KuwarpratapSingh: If this answer solved your problem, please mark it as accepted. If you need something else, please ask a new question. BR – Roar S. Dec 21 '20 at 18:23