Home > other >  .NETCore and how to use AJAX Post Request to update SQL database
.NETCore and how to use AJAX Post Request to update SQL database

Time:11-24

I am working on a .NETCore application and I want to use a jQuery AJAX Post call to update my SQL database when a button is clicked. I have tried a couple of different variations of ajax calls but nothing is working. I either receive a 404 or 400 error. I am not sure what I am doing wrong. Below is the code for my ajax call

$("#addMilestoneBtn").on('click', function (e) {
    e.preventDefault();
    var milestoneDetails = {};
    var date = $("#milestoneDate").val();

    milestoneDetails.MilestoneName = $("#milestoneText").val();
    milestoneDetails.Date = new Date(date);
    milestoneDetails.Date.setHours(0, 0, 0, 0);
    milestoneDetails.ProjectId = Number($("#projectId").val());

    var jsonData = JSON.stringify(milestoneDetails);

    var url = '@Url.Action("AddMilestone","HomeController")';

    $.ajax({
        type: "POST",
        url: url,
        data: jsonData,    
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        error: one rrorCall
    });

    function OnSuccess(response) {
        var result = response.d;
        if (result == "success") {
            alert("Milestone Added Sucessfully")
            //$("#").html("Milestone addded successfully").css("color", "green");
            buildMilestoneTable();
        }
        $("#milestoneDate").val("");
        $("#milestoneText").val("");  

    }

    function OnErrorCall(response) {
        //$("#").html("An Error has occurred. Please Try Again!").css("color", "red");
        console.log(response); 
    }
  
    return false; 

}); 

For the ajax call I have tried @Url.Action to create the url. I have also tried using the controller and action name like this: '/HomeController/AddMilestone'.

Here is the code for my Controller:

[HttpPost]
    public bool AddMilestone(HomeViewModel obj)
    {
        //Create new Milestone
        obj.Milestone.Date = DateTime.Today;
        obj.Milestone.MilestoneName = obj.Milestone.MilestoneName;
        obj.Milestone.ProjectId = obj.Project.Id;
        _db.Milestones.Add(obj.Milestone);
        _db.SaveChanges();

        return true;
    }

Here is the code for my HomeViewModel:

   public class HomeViewModel
{
    public Project Project{ get; set; }
    public IEnumerable<Project> Projects { get; set; }
    public IEnumerable<SelectListItem> TeamDropDown { get; set; }
    public IEnumerable<SelectListItem> GroupDropDown { get; set; }
    public IEnumerable<SelectListItem> StatusDropDown { get; set; }
    public IEnumerable<SelectListItem> NotesDropDown { get; set; }
    public IEnumerable<SelectListItem> NetworkDropDown { get; set; }
    public IEnumerable<SelectListItem> AssigneeDropDown { get; set; }
    public GTMNote GTMNote { get; set; }
    public SECNote SECNote { get; set; }
    public OPSNote OPSNote { get; set; }
    public LCNote LCNote { get; set; }
    public CTRNote CTRNote { get; set; }
    public Update Update { get; set; }
    public Milestone Milestone { get; set; }  
    public NextStep NextStep { get; set; }

}

Here is the HTML part of my form:

       <div class="tab-pane" id="milestones" role="tabpanel">
                    <br />
                    <fieldset class="form-group">
                        <input class="form-control col-2" asp-for="Milestone.Date" type="text" value="@ViewBag.DateNoTime" id="milestoneDate">
                    </fieldset>
                    <fieldset class="form-group">
                        <input class="form-control" type="text" asp-for="Milestone.MilestoneName" oninput="charLimit();" id="milestoneText" />
                        <p>
                            <small class="text-danger" id="milestoneValidation" style="padding-top: 10px; display: none;">Please provide milestone text.</small>

                        </p>
                    </fieldset>
                    <br />
                    <a class="btn btn-primary" id="addMilestoneBtn">Add Milestone</a>
                    <br />
                    <div id="milestoneTable"></div>
                </div>

Milestone Class:

public class Milestone
{
    [Key]
    public int Id { get; set; }
    [DisplayName("")]
    public string MilestoneName { get; set; }
    [DisplayName("Milestone Date")]
    public DateTime Date { get; set; }

    //Forgein Keys
    public int ProjectId { get; set; }
    [ForeignKey("ProjectId")]
    public Project Project { get; set; }
}

Thank you in advance for your help!

CodePudding user response:

try to send this data

  var milestoneDetails = {
    MilestoneName : $("#milestoneText").val(),
    ProjectId :$("#projectId".val()
};
  var jsonData = JSON.stringify(milestoneDetails);
  var url = '@Url.Action("AddMilestone","HomeController")';
  // or try , if you get 404
var url = '/Home/AddMilestone';

and use this action, add [FromBody] since you are using "application/json" contentType

    [HttpPost("~/Home/AddMilestone")]
    public bool AddMilestone([FromBody] Milestone mileStone)
    {
       
        mileStone.Date = DateTime.Today;
       
        _db.Milestones.Add(mileStone);
        _db.SaveChanges();

        return true;
    }
   
  • Related