Home > Software engineering >  C# MVC update database with ajax and json
C# MVC update database with ajax and json

Time:04-20

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 >
<div ></div>
<div >
    <div >
        <label>First Name :</label>
        <input  type="text" id="txtFirstName" required />
    </div>
    <div >
        <label>Last Name :</label>
        <input  type="text" id="txtLastName" required />
    </div>
    <div >
        <br />
        <input id="btnSave"  type="button" value="Save Product" />
        <input id="btnCancel"  type="button" value="Cancel" />
    </div>
</div>
</div>

<div id="dvLoader"  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!

CodePudding user response:

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)
  • Related