不工作jQuery ajax将数据插入ASP.NET MVC 5中的数据库

时间:2021-05-06 15:41:16

I can't figure out what error I have in my code. I have checked carefully and tried to insert data into a SQL Server database. But every time it shows "Internal server error" while submitting the form. Please help me to figure out. Thanks

我无法弄清楚我的代码中有什么错误。我仔细检查过并尝试将数据插入SQL Server数据库。但每次提交表单时都会显示“内部服务器错误”。请帮我搞清楚。谢谢

Here is my code..

这是我的代码..

Database table:

CREATE TABLE [dbo].[Doctor] 
(
    [DoctorID]        INT IDENTITY (1, 1) NOT NULL,
    [DoctorCardID]    AS ('DOC' + RIGHT('000' + CONVERT (VARCHAR (3), [DoctorID]), (3))),
    [DoctorName]      VARCHAR(50)  NOT NULL,
    [Gender]          VARCHAR(20)  NOT NULL,
    [ContactNumber]   VARCHAR(11)  NOT NULL,
    [DoctorAvatar]    VARCHAR(500) NULL,
    [Dob]             DATE         NULL,
    [Address]         VARCHAR(50)  NULL,
    [City]            VARCHAR(50)  NULL,
    [ZipCode]         NCHAR(10)    NULL,
    [QualificationID] INT          NULL,
    [SpecialityID]    INT          NULL,
    [JoiningDate]     DATETIME     NOT NULL,
    [AddeddDate]      DATE         NULL,
    [IsActive]        BIT          DEFAULT ((1)) NULL,

    PRIMARY KEY CLUSTERED ([DoctorID] ASC),
    FOREIGN KEY ([QualificationID]) 
        REFERENCES [dbo].[Qualification] ([QualificationID]),
    FOREIGN KEY ([SpecialityID]) 
        REFERENCES [dbo].[Speciality] ([SpecialityID])
);

Jquery and Ajax code:

Jquery和Ajax代码:

$('#doctor-submit').click(function(e) {
                e.preventDefault();
                var data = JSON.stringify({
                        DoctorName: $('#DoctorName').val(),
                        Gender: $('#Gender').val(),
                        ContactNumber: $('#ContactNumber').val(),
                        Dob: $('#Dob').val(),
                        Address: $('#Address').val(),
                        City: $('#City').val(),
                        ZipCode: $('#ZipCode').val(),
                        QualificationID: $('#QualificationID').val(),
                        SpecialityID: $('#SpecialityID').val(),
                        JoiningDate: $('#JoiningDate').val(),
                        AddeddDate: $('#AddeddDate').val(),
                        IsActive: $('#IsActive').val()
                });
                $.ajax({
                    url: "@Url.Action("Create", "Doctor")",
                    type: "POST",
                    data: data,
                    processData : false,
                    contentType: "application/json; charset=utf-8",
                    dataType:"json",
                    cache:false,
                    success: function (response) {
                        $('#show-success').show();
                    }

                });
            });

ASP.NET MVC form:

ASP.NET MVC表单:

<form id="DoctorForm" enctype="multipart/form-data">
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Doctor</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    @Html.LabelFor(model => model.DoctorName, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.DoctorName, new { htmlAttributes = new { @class = "form-control", @id = "DoctorName" } })
                        @Html.ValidationMessageFor(model => model.DoctorName, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control", @id = "Gender" } })
                        @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.ContactNumber, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.ContactNumber, new { htmlAttributes = new { @class = "form-control", @id = "ContactNumber" } })
                        @Html.ValidationMessageFor(model => model.ContactNumber, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Dob, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.Dob, new { htmlAttributes = new { @class = "form-control", @id = "Dob" } })
                        @Html.ValidationMessageFor(model => model.Dob, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control", @id = "Address" } })
                        @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control", @id = "City" } })
                        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.ZipCode, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { @class = "form-control", @id = "ZipCode" } })
                        @Html.ValidationMessageFor(model => model.ZipCode, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.QualificationID, "QualificationID", htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.DropDownList("QualificationID", null, htmlAttributes: new { @class = "form-control", @id = "QualificationID" })
                        @Html.ValidationMessageFor(model => model.QualificationID, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.SpecialityID, "SpecialityID", htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.DropDownList("SpecialityID", null, htmlAttributes: new { @class = "form-control", @id = "SpecialityID" })
                        @Html.ValidationMessageFor(model => model.SpecialityID, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.JoiningDate, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.JoiningDate, new { htmlAttributes = new { @class = "form-control", @id = "JoiningDate" } })
                        @Html.ValidationMessageFor(model => model.JoiningDate, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.AddeddDate, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        @Html.EditorFor(model => model.AddeddDate, new { htmlAttributes = new { @class = "form-control", @id = "AddeddDate" } })
                        @Html.ValidationMessageFor(model => model.AddeddDate, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-4" })
                    <div class="col-md-8">
                        <div class="checkbox">
                            @Html.EditorFor(model => model.IsActive, new { @id = "IsActive" })
                            @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <input id="doctor-submit" type="submit" value="Create" class="btn btn-default" />
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">

                    <div class="col-md-12">
                        <img src="~/Content/images/man.jpg" id="processImage" class="process-image img-responsive" />
                        <div class="upload-box">
                            <input id="imageFile" name="ImageUpload" type="file" accept="image/jpeg, image/png" alt="Photo" class="image-file" />
                            <div class="upload-icon">
                                <i class="menu-icon fa fa-upload"></i> Upload
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

<div id="show-success" class="success-save alert alert-block alert-success">
    <button type="button" class="close" data-dismiss="alert">
        <i class="ace-icon fa fa-times"></i>
    </button>

    <p>
        <strong>
            <i class="ace-icon fa fa-check"></i>
            Well done!
        </strong>
        Doctor Save successfully!
    </p>
</div>
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

Controller code:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( Doctor doctor)
{
    if (ModelState.IsValid)
    {
        if (doctor.ImageUpload != null)
        {
            string filename = Path.GetFileNameWithoutExtension(doctor.ImageUpload.FileName);
            string extension = Path.GetExtension(doctor.ImageUpload.FileName);
            filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
            doctor.DoctorAvatar = "~/Content/images/DoctorsImg/" + filename;
            doctor.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/Content/images/DoctorsImg"), filename));
        }

        db.Doctors.Add(doctor);
        db.SaveChanges();

        return RedirectToAction("Index", "Doctor");
    }

    ViewBag.QualificationID = new SelectList(db.Qualifications, "QualificationID", "QualificationName", doctor.QualificationID);
    ViewBag.SpecialityID = new SelectList(db.Specialities, "SpecialityID", "SpecialityTag", doctor.SpecialityID);

    return Json(new { success = true });
}

1 个解决方案

#1


0  

I think the problem is with ValidateAntiForgeryToken as you are not submitting the form. You are making an Ajax request hence the anti forgery token validation fails. Remove this and try again.

我认为问题在于ValidateAntiForgeryToken,因为您没有提交表单。您正在发出Ajax请求,因此防伪令牌验证失败。删除它,然后再试一次。

#1


0  

I think the problem is with ValidateAntiForgeryToken as you are not submitting the form. You are making an Ajax request hence the anti forgery token validation fails. Remove this and try again.

我认为问题在于ValidateAntiForgeryToken,因为您没有提交表单。您正在发出Ajax请求,因此防伪令牌验证失败。删除它,然后再试一次。