0

I have a simple form on a C# MVC View. The form collects users first and last name and then should send the data the controller. This is what the form looks like:

<div class="col-md-12">
<div class="col-md-4"></div>
<div class="col-md-4">
    <div class="col-md-12">
        <label>First Name :</label>
        <input class="form-control required" type="text" id="txtFirstName" required />
    </div>
    <div class="col-md-12">
        <label>Last Name :</label>
        <input class="form-control required" type="text" id="txtLastName" required />
    </div>
    <div class="col-md-12">
        <br />
        <input id="btnSave" class="btn btn-success" type="button" value="Save Product" />
        <input id="btnCancel" class="btn btn-danger" type="button" value="Cancel" />
    </div>
</div>
</div>

<div id="dvLoader" class="LoadingDiv" style="display: none;">
<table style="height: 100%; margin: auto;">
    <tr>
        <td style="vertical-align: middle;">
            <center>
                <img src="..\..\Images\loading-icegif.gif" alt="Loading" />
            </center>
        </td>
    </tr>
</table>
</div>

And I have this ajax code:

        $(function () {
        $('#btnSave').on('click', function () {
            var FirstName = $("#txtFirstName").val();
            var LastName = $("#txtLastName").val();
            if (CheckRequiredFields()) {
                $('#dvLoader').show();
                $.ajax({
                    url: '@Url.Action("SaveAndUpdateProduct", "Home")',
                        type: 'POST',
                        data: JSON.stringify({ "FirstName": FirstName, "LastName": LastName }),
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        success: function (result) {
                            $('#dvLoader').hide();

                            if (result.Status == "True") {
                                toastr.success(result.Message);
                                clear();
                                display();
                            }
                            else {
                                toastr.success(result.Message);
                                clear();
                                display();

                            }
                        }
                    });
            }
        });
    });

And, this is HomeController.cs:

using CodingChallengeV4.Models;
using Docker.DotNet.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CodingChallengeV4.Controllers
{
public class HomeController : Controller
{
    public ActionResult Index()
    {
        using (var ctx = new ContactContext())
        {
            var seedContact = new ContactOrig();
            seedContact.FirstName = "seelFirst";
            seedContact.LastName = "seedLast";

            ctx.Contact.Add(seedContact);
            ctx.SaveChanges();
        }
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Message = "Your application description page.";
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
    public JsonResult SaveAndUpdate(string FirstName, string LastName)
    {
        var result = new JSONMessage();
        try
        {
            using (var ctx = new ContactContext())
            {
                //define the model  

                var contact = new ContactOrig();
                contact.FirstName = FirstName;
                contact.LastName = LastName;

                ctx.Contact.Add(contact);
                result.Status = "true";
                result.ErrorMessage = "your product has been updated successfully..";
                ctx.SaveChanges();
            }

        }
        catch (Exception ex)
        {
            result.ErrorMessage = "We are unable to process your request at this time. Please try again later.";
            result.Status = "false";
        }
        return Json(result, JsonRequestBehavior.AllowGet);
    }
}

}

When I execute the code, and I enter a first and last name and click the Save button, the dvLoader gets displayed but I get this error in the console:

POST http://localhost:4093/Home/SaveAndUpdateProduct 500 (Internal Server Error)

Any idea why the post is generating this error?

Thanks!

5
  • what happens when you step through and debug the backend code? Commented Apr 19, 2022 at 22:22
  • additionally, can you share your code for the backend where the endpoint is that is being hit, and also the code where this is breaking and causing the 500 Commented Apr 19, 2022 at 22:28
  • @SimonPrice: it never hits any breakpoint in the controller. I have a breakpoint set on the first line of code in the controller (var result = new JSONMessage(); but the breakpoint is never hit. Commented Apr 19, 2022 at 22:52
  • if youre getting a 500, its hitting somewhere, make sure youre symbols are being loaded, and also , can you edit your question to show your controller code please, we cannot help you with out this as this would be purely guess work Commented Apr 19, 2022 at 23:27
  • youre alos json stringifying, a json string Commented Apr 19, 2022 at 23:27

1 Answer 1

1

For the start, it would be nice to create a view model

public class NameViewModel
{
      public string FirstName {get; set;}
      public string LastName {get; set;}
}

try to remove contentType: "application/json; charset=utf-8" from ajax

$.ajax({
    url: "/Home/SaveAndUpdateProduct",
      type: 'POST',
       data: { FirstName: FirstName, LastName: LastName },
       dataType: "json",

and fix the action

 public JsonResult SaveAndUpdateProduct(NameViewModel model)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.