Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a form where I'm adding some values in DB using AJAX and I've made all the logic to avoid adding if there is some duplicated value, but I want to show a simple message below id="txtTitle" input, that "such number already exists". Until now I've tried to show an alert message, after button click, but it doesn't work. Can somebody tell me what I'm doing wrong here?

What I have tried:

This is my controller:
C#
[HttpPost]
public JsonResult AddNewEvent(Event e)
{
    try { 
        using(EventsDBEntities db = new EventsDBEntities())
        {
            List<Event> evts = db.Events.Where(x => x.Title == e.Title).ToList();
                
            if(evts.Count > 0)
            {
                TempData["Message"] = "<script>alert('This order number already exists, please check it and try again');</script>";
            }
            else
            {
                db.Events.Add(e);
                db.SaveChanges();
            }
        }
    }
    catch(Exception)
    {
    }
    
    return new JsonResult { Data = e,  JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

My MVC View:
Razor
<div class="modal modal-dialog-centered" id="AddEventCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLongTitle">Add new Event:</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">×</span>
            </button>
        </div>
        <div class="modal-body" style="width:auto">

            <div id="dialog-edit" style="width:auto"></div>

            <div id="AddEvent">

                <table style="width:500px;">
                    <tr>
                        <td>
                            <select id="colorChoose">
                                <option value="white">
                                    ---choose---
                                </option>
                                <option value="green">
                                    Maintenance(46535..., 4683...)
                                </option>
                                <option value="yellow">
                                    Field repair(46303..., 4681...)
                                </option>
                                <option value="grey">
                                    Warranty(967..., 968...)
                                </option>
                            </select>
                            <br />
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td style="width:250px;">
                            <label>Order number :</label><br />
                            <input maxlength="15" style="width:200px;" type="text" id="txtTitle" />
                            // here must be message if Duplicate<input id="ifDuplicate" />
                        </td>

                        <td style="width:250px;">
                            <label>Event Title :</label><br />
                            <input maxlength="20" style="width:200px;" type="text" id="txtDesc" />
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <br />
                            <label>Full event description:</label>
                            <br />
                            <textarea maxlength="500" style="height:100px;width:500px;resize:none;" id="txtFullDesc"></textarea>
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td style="width:250px;padding-right:7em;">
                            <label>Address :</label><br />
                            <textarea maxlength="100" style="height:100px;width:200px;resize:none;" id="txtAddress"></textarea>
                        </td>

                        <td style="width:250px;">
                            <label>Contact peson on site :</label><br />
                            <textarea maxlength="100" style="height:100px;width:200px;resize:none;" id="txtContact"></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td style="width:200px;">
                            <br />
                            <label>Location title :</label>
                            <br />
                            <input maxlength="15" style="width:200px;" type="text" id="txtLoc" />
                            <br />
                            <br />
                            <input style="width:200px;" type="hidden" id="colorAdd" />
                        </td>

                    </tr>
                </table>

            </div>


        </div>
        <div class="modal-footer">
            <button type="button" id="btnAdd" onclick="return Add();" class="btn btn-primary" data-dismiss="modal">Add new event</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
    </div>
</div>

Javascript:
JavaScript
// This is for Add new Data
function Add() {
    
    $.ajax({
        type: "POST",
        url: "/Home/AddNewEvent",
        dataType: "JSON",
        data: {
            Title: $('#txtTitle').val(),
            Description: $('#txtDesc').val(),
            Location: $('#txtLoc').val(),
            color: $('#colorAdd').val(),
            fullDescription: $('#txtFullDesc').val(),
            Address: $('#txtAddress').val(),
            Contact: $('#txtContact').val()
        },
        success: function () {
            
            $('#UpdatePanel').load(loadData());
            var res = "";
            $('#txtTitle').val(res),
                $('#txtDesc').val(res),
                $('#txtLoc').val(res),
                $('#colorAdd').val(res),
                $('#txtFullDesc').val(res),
                $('#txtAddress').val(res),
                $('#txtContact').val(res)
        },
        error: function () {
            alert("Failed! Please try again.");
        }
    });
}
Posted
Updated 6-Jul-20 1:16am
v2

1 solution

Change the shape of the data you're returning:
C#
[HttpPost]
public JsonResult AddNewEvent(Event e)
{
    try 
    { 
        using(EventsDBEntities db = new EventsDBEntities())
        {
            if (db.Events.Any(x => x.Title == e.Title))
            {
                return Json(new { data = e, success = false, error = "This order number already exists, please check it and try again" }, JsonRequestBehavior.AllowGet);
            }
            
            db.Events.Add(e);
            db.SaveChanges();
            
            return Json(new { data = e, success = true }, JsonRequestBehavior.AllowGet);
        }
    }
    catch (Exception ex)
    {
        return Json(new { data = e, success = false, error = ex.Message }, JsonRequestBehavior.AllowGet);
    }
}
Then update your Javascript to use the new data:
JavaScript
function Add() {
    
    $.ajax({
        type: "POST",
        url: "/Home/AddNewEvent",
        dataType: "JSON",
        data: {
            Title: $('#txtTitle').val(),
            Description: $('#txtDesc').val(),
            Location: $('#txtLoc').val(),
            color: $('#colorAdd').val(),
            fullDescription: $('#txtFullDesc').val(),
            Address: $('#txtAddress').val(),
            Contact: $('#txtContact').val()
        },
        success: function (result) {
            if (!result.success) {
                alert(result.error);
                return;
            }
            
            $('#UpdatePanel').load(loadData());
            $('#txtTitle').val("");
            $('#txtDesc').val("");
            $('#txtLoc').val("");
            $('#colorAdd').val("");
            $('#txtFullDesc').val("");
            $('#txtAddress').val("");
            $('#txtContact').val("");
        },
        error: function () {
            alert("Failed! Please try again.");
        }
    });
}
If you want to display the error message somewhere in your form, rather than displaying an alert, change the alert(result.error) line to update the contents of the target element:
JavaScript
if (!result.success) {
    $("your-target-element-selector").text(result.error);
    return;
}
 
Share this answer
 
Comments
Member 14803832 6-Jul-20 7:17am    
Thaks You, looks good. Will try this out an give You my feedback, but I'm pretty sure it will work :)
Member 14803832 6-Jul-20 12:08pm    
Works perfectley, as I thought! Thank You!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900