【问题标题】:How to use ajax call to insert data without postback in mvc?如何使用ajax调用在mvc中插入数据而不回发?
【发布时间】:2016-06-23 11:41:35
【问题描述】:

我使用 ado.net 实体数据模型添加了模型。我想插入 数据库表中的数据没有回发,所以我使用了 ajax 和 jquery 但我没有得到输出。我是 mvc 和 ajax 的新手。

这是我的视图文件:

@model ajaxJquery.Models.register

@{
    ViewBag.Title = "Index";
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#Register").click(function () {
            //var studentid = $("#studnt_id").val();
            var Name = $("#name").val();

            var Qualification = $("#qualification").val();

            var Branch = $("#branch").val();

            var Gender = $("#gender").val();

            var State = $("#state").val();

            var LoginId = $("#login_id").val();

            var Password = $("#password").val();


                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("Index","Home")',

                    data: "{'name':'" + Name + "','studentId':'" + studentid + "','qualification':'" + Qualification + "','branch':'" + Branch + "','gender':'" + Gender + "','state':'" + State + "','loginid':'" + LoginId + "','password':'" + Password + "'}",
                    success: function (data) {
                        if (data == true) {

                            $("#divresult").text("recorded successfully");
                        }
                        else {

                            $("#divresult").text("couldnot save record");
                        }
                    },
                    error: function () {
                        //Show error message(if occured)
                        $('#divresult').text("Error: ");
                    }



                });

                return false;


            });



    });



    </script>
<h2>Index</h2>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>register</legend>

        @*<div class="editor-label">
            @Html.LabelFor(model => model.studnt_id)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.studnt_id)
            @Html.ValidationMessageFor(model => model.studnt_id)
        </div>*@

        <div class="editor-label">
            @Html.LabelFor(model => model.name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.name)
            @Html.ValidationMessageFor(model => model.name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.qualification)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.qualification)
            @Html.ValidationMessageFor(model => model.qualification)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.branch)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.branch)
            @Html.ValidationMessageFor(model => model.branch)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.gender)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.gender)
            @Html.ValidationMessageFor(model => model.gender)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.state)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.state)
            @Html.ValidationMessageFor(model => model.state)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.login_id)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.login_id)
            @Html.ValidationMessageFor(model => model.login_id)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.password)
            @Html.ValidationMessageFor(model => model.password)
        </div>

        <p>
            <input type="submit" value="Create"  id="Register"/>
        </p>


    </fieldset>
}
<div id="divresult"></div>
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

这是我的控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ajaxJquery.Models;

namespace ajaxJquery.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {

            return View();
        }
        [HttpPost]
        public ActionResult Index( string name, string qualification, string branch, string gender, string state, string loginid, string Password)
        {
            ajaxcontext db = new ajaxcontext();
            register reg = new register();
            //reg.studnt_id = studentId;
            reg.name = name;
            reg.qualification = qualification;
            reg.branch = branch;
            reg.gender = gender;
            reg.state = state;
            reg.login_id = loginid;
            reg.password = Password;
            db.registers.Add(reg);
            db.SaveChanges();
            return View();
        }

    }
}

【问题讨论】:

  • 浏览器控制台是否出现错误?您的 ajax 调用是否到达服务器端 Action?

标签: jquery ajax asp.net-mvc-3 model-view-controller


【解决方案1】:

添加 preventDefault 以防止表单提交。

 $("#Register").click(function (e) {
    e.preventDefault()
    ...
 }

你也可以用 :

序列化表单
data : $('#myForm').serialize()

移除点击,绑定提交事件:

@section scripts{
    <script type="text/javascript">

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

        $(function () {
            $("#myForm").submit(function (event) {

            var a = $('#myForm').serializeObject();
            var data = JSON.stringify(a);

            alert(data);

                $.ajax({
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    url: '@Url.Action("Index","Home")',

                    data: data,
                    success: function (data) {
                        console.log(data);
                        if (data == true) {
                            $("#divresult").text("recorded successfully");
                        } else {
                            $("#divresult").text("couldnot save record");
                        }
                    },
                    error: function (request, status, error) {
                        alert(request.responseText);
                        $('#divresult').text("Error: " + request.responseText);
                    }
                });

                event.preventDefault();
            });
        });
    </script>
}

你可以像这样给出form和id;

@using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { id = "myForm" })) {

}

[HttpPost]
public ActionResult Index(string name, string qualification, string branch, string gender, string state, string loginid, string Password)
{
    ...
    return View();
}

【讨论】:

  • 当我使用 e.preventDefault() 时,它没有使用 ajax 调用 @irfan 运行代码
  • 我已经更新了我的答案。保持控制台打开以防出错。
  • 如何在控制器动作中调用表单数据。我在动作中传递表单集合对象但我没有得到@irfan
  • 公共 ActionResult 索引(注册注册){}
  • 首先它没有达到我在 url 中提到的动作
猜你喜欢
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 2016-06-23
  • 2017-10-06
相关资源
最近更新 更多