0

I'm trying to implement AJAX to update the existing record in my database, but it is neither showing "success" message nor "error" message. I have saved id of variable in "value" by "value = Model.ID". I passed the correct row from my controller.

Script code:

$("#button").click(function () {
    var upid = $('#hide').val();
        var values = {
            Email: $('#txtEmail').val(),
            FirstName: $('#fname').val(),
            LastName: $('#lname').val(),
            MobileNumber: $('#num').val(),
            DateOfBirth: $('#dob').val(),
            Password: $('#pwd').val(),
    }
    $.ajax({
        url: '/Populations/UpdatePopulation',
        method: 'POST',
        data: {
            std: values,
            id: upid
        },
        success: function () {
            alert("Updated");
        },
        error: function (jqXHR) {
            $('#divErrorText').text(jqXHR.responseText);
        
        }
    });
    });

Controller(for making updates):

 [HttpPost]
        public ActionResult UpdatePopulation(Population std, int id)
        {
            
            {
                Population updatestd = db.Populations.Find(id);
                if (!string.IsNullOrWhiteSpace(std.Email)) { updatestd.Email = std.Email; }
                if (!string.IsNullOrWhiteSpace(std.FirstName)) { updatestd.FirstName = std.FirstName; }
                if (!string.IsNullOrWhiteSpace(std.LastName)) { updatestd.LastName = std.LastName; }
                { updatestd.MobileNumber = std.MobileNumber; }
                { updatestd.DateOfBirth = std.DateOfBirth; }
                 { updatestd.Password = std.Password; }
                db.SaveChanges();
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }

Html code without _layout.cshtml file:

@model OfficeWork.Models.Population

@{
    ViewBag.Title = "Edit";
}
@{
    var value = Model.ID;
}

@section navbar{
    <div class="container-fluid">
        <div class="navbar-header">
            <P class="navbar-brand">PROJECT</P>
        </div>
        <ul class="nav navbar-nav">
            <li class="active" style="cursor:pointer;"><a>User Details</a></li>

        </ul>

        <ul class="nav navbar-nav navbar-right">
            <li>@Html.ActionLink(" Log Out", "SignIn", "populations", htmlAttributes: new { @class = "glyphicon glyphicon-user" })</li>

        </ul>
    </div>
}


<div class="container" style="margin-top:10%">
    <form method="post">

        <div class="form-horizontal">
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @type = "email", @placeholder = "Enter email", @id = "txtEmail" } })
                    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.FirstName, new
               {
                   htmlAttributes = new { @class = "form-control", @type = "text", @id = "fname", @placeholder = "Frist Name" }
               })
                    @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", @type = "text", @id = "lname", @placeholder = "Last Name" } })
                    @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.MobileNumber, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.MobileNumber, new { htmlAttributes = new { @class = "form-control", @id = "num", @placeholder = "Mobile Number" } })
                    @Html.ValidationMessageFor(model => model.MobileNumber, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control", @type = "date", @id = "dob" } })
                    @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", @type = "password", @id = "pwd", @placeholder = "Enter password", @onkeyup = "Check()" } })
                    @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <label class="control-label col-sm-2" for="renterpwd">Repeat Password:</label>
                <div class="col-sm-10">
                    <input type="password" class="form-control" id="renterpwd" placeholder="Repeat password" onkeyup="Check()">
                    <span id="error"></span>
                </div>

            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save Details" class="btn btn-default" id="button" />
                </div>
            </div>
        </div>
    </form>
    <br />
    <div id="divErrorText"></div>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/js")
}
<input id="hide" type="hidden" value="@value" />

Modal class:

using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace OfficeWork.Models
{
    public class Population
    {
        [Key]
        public int ID { get; set; }
        [Required]
        [Display(Name ="Email")]
        [EmailAddress(ErrorMessage ="Enter valid email address")]
        public string Email { get; set; }
        [StringLength(10)]
        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [StringLength(10)]
        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        [Display(Name = "Mobile Number")]
        [Required]
        public long MobileNumber { get; set; }
        [Display(Name = "Date Of Birth")]
        [Required]
        public DateTime DateOfBirth { get; set; }
        [Display(Name = "Password")]
        [Required]
        public string Password { get; set; }
    }

    public class PopulationDBContext : DbContext
    {
        public DbSet<Population> Populations { get; set; }
    }

}

I tried to execute "alert" message in my script to check whether my script uploaded successfully and it worked fine. This means I successfully uploaded my script though "bundle.config" file. "bundles.Add(new ScriptBundle("~/bundles/js").Include("~/Scripts/Edit.js"));"

1
  • Please confirm two things: 1. Does the request go to the server (through F12 in the browser). 2. Does the request come to the method that you expect (put some Log message or just breakpoint and debug). Layout and even Model (not Modal) are probably irrelevant to your question - you may want to remove them Commented May 8, 2021 at 16:51

1 Answer 1

0

fix you submit button by removing submit type

  <input value="Save Details" class="btn btn-default" id="submitButton" />

and try to wrap your script

$(document).ready(function () {

$(document).on("click", "#submitButton",
        function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();

    ....  your code
       success: function (result) {
            alert("Updated");
        },
 .... your code
  
    });
});

and check up developer tools in your browser for javascript errors

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.