Home > Software design >  controller method not returning any response after successful execution
controller method not returning any response after successful execution

Time:11-18

I am posting my data using Ajax, the data is successfully posted to the database. But I am not getting response back from the Create Method. I mean return RedirectToAction("Index"); the page is not redirecting to Index page.

// POST: TestModels/Create        
[HttpPost]
public ActionResult Create(TestModel testModel)
{
    if (ModelState.IsValid)
    {
        db.TestModels.Add(testModel);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(testModel);
}

Also, I tried:

// POST: TestModels/Create        
[HttpPost]
public JsonResult Create(TestModel testModel)
{
    if (ModelState.IsValid)
    {
        db.TestModels.Add(testModel);
        db.SaveChanges();
       return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);     
    }
    return Json(new { success = false, responseText = "Error." }, JsonRequestBehavior.AllowGet);
}

Still I am not getting any Json response.

My javascript function::

<script>
    $(document).ready(function () {
        $('#btn_submit').click(function () {

            var testModel = {
                FirstName: $('#FirstName').val(),
                LastName: $('#LastName').val(),
                Gender: $("input[name='Gender']:checked").val(),
                Contact: $('#Contact').val(),
                Faculty: $('#Faculty').val(),
                RegNepaliDate: $('#RegNepaliDate').val()
            };
            alert(JSON.stringify(testModel));

            $.ajax({
                type: "POST",
                url: "/TestModels/Create", 
                data: JSON.stringify(testModel),
                contentType: "application/json;charset=utf-8",
                dataType: 'json',
                success: function (response) {
                    console.log(response);
                    if (response.success) {
                        console.log(response.responseText);
                        console.log(data);
                    }
                },
                error: function (response) {
                    alert("failed...");
                  }  
            })

        })
    })
</script>

The data is posted to the server and when I browse Index page the newly inserted data is also shown. Also, when I click the submit button of the Create page, the form data becomes clear but all the data is shown in the url bar

https://localhost:44399/TestModels/Create?FirstName=machhi&LastName=go&Gender=male&Contact=5589512369&Faculty=science&RegNepaliDate=2021-05-01

CodePudding user response:

Could you please add missing jQuery library file like "

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery-3.4.1.slim.min.js"></script>

" to get the response from Controller.

  • Related