【问题标题】:Using Ajax to Update database in ASP.net MVC在 ASP.net MVC 中使用 Ajax 更新数据库
【发布时间】:2021-05-08 16:43:22
【问题描述】:

我正在尝试实施 AJAX 来更新数据库中的现有记录,但它既没有显示“成功”消息,也没有显示“错误”消息。 我已经通过“value = Model.ID”在“value”中保存了变量的 id。我从控制器传递了正确的行。

脚本代码:

$("#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);
        
        }
    });
    });

控制器(用于更新):

 [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);
        }

没有 _layout.cshtml 文件的 HTML 代码:

@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" />

模态类:

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; }
    }

}

我尝试在我的脚本中执行“警报”消息,以检查我的脚本是否成功上传并且工作正常。这意味着我通过“bundle.config”文件成功上传了我的脚本。 "bundles.Add(new ScriptBundle("~/bundles/js").Include("~/Scripts/Edit.js"));"

【问题讨论】:

  • 请确认两件事: 1.请求是否到达服务器(通过浏览器中的F12)。 2.请求是否到达您期望的方法(放置一些日志消息或只是断点和调试)。布局甚至模型(不是 Modal)可能与您的问题无关 - 您可能想要删除它们

标签: asp.net asp.net-mvc


【解决方案1】:

通过删除提交类型修复提交按钮

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

并尝试包装你的脚本

$(document).ready(function () {

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

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

并检查浏览器中的开发者工具是否存在 javascript 错误

【讨论】:

  • @AnirudhRawat 我很高兴它有帮助。请不要忘记接受答案。
猜你喜欢
  • 2015-04-20
  • 2018-09-09
  • 2016-11-25
  • 2021-12-10
  • 2017-09-09
  • 1970-01-01
  • 2017-08-12
  • 1970-01-01
  • 2020-04-16
相关资源
最近更新 更多