【问题标题】:How to insert a row into a database using AJAX and MVC C#?如何使用 AJAX 和 MVC C# 在数据库中插入一行?
【发布时间】:2015-07-02 23:28:57
【问题描述】:

我有一个问题,我想使用 C# MVC AJAX 在我的数据库中添加一个新行,但它不起作用。我可以看到文本框的值作为 URL 中的参数,但是当我单击提交按钮时,它不起作用,我不知道如何继续。你能帮我解决这个问题吗?这是代码:

我在Controller中包含插入指令的方法:

public void AddCategorie(string cat)
{
    Category cate = new Category();
    cate.CategoryNom = cat;
    db.Categories.Add(cate);
    db.SaveChanges();
}

我在视图中显示结果的代码:

@{
    ViewBag.Title = "Gestion des catégories";
}

<hgroup class="title">
    <h1>@ViewBag.Title</h1>
</hgroup>

<section class="contact">
    <form ng-model="AddCategorie()">
        <input type="text" name="name" placeholder="Nouvelle catégorie" /><br />
        <input type="submit" value="Ajouter" />
    </form>
    <input type="submit" value="Modifier" />
    <input type="submit" value="Supprimer" />
</section>

索引中的代码(也许它可以提供帮助)它显示了应用程序的主页:

@{
    ViewBag.Title = "Home Page";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.4/handlebars.min.js"></script>
<script src="http://bootswatch.com/spacelab/bootstrap.min.css"></script>

@*<script src="jquery.min.js"></script>
<script src="jssor.slider.mini.js"></script>
<script>
    jQuery(document).ready(function ($) {
        var options = { $AutoPlay: true };
        var jssor_slider1 = new $JssorSlider$('slider1_container', options);
    });
</script>*@

<style>
    .categories, .animes, .perso {
        color: #000;
        margin-left: 35px;
    }
</style>


<script>
    templateCategories = null;
    templateAnimes = null;
    templatePerso = null;

    $(function () {
        templateCategories = Handlebars.compile($('#CategoriesTemplate').html());
        templateAnimes = Handlebars.compile($('#AnimesTemplate').html());
        templatePerso = Handlebars.compile($('#PersoTemplate').html());

        $.getJSON("Animes/GetCategories", null, function (data) {
            var result = templateCategories(data);

            $('#CategoriesOutput').html(result);
        });
    });

    function GetAnimes(catID) {
        $.getJSON("Animes/GetAnimes", { categoryID: catID }, function (data) {
            var resAnimes = templateAnimes(data);

            $('#AnimesOutput').html(resAnimes);
            $('lstCat').html(resAnimes);
        });
    }

    function GetPersonnages(aniID) {
        $.getJSON("Animes/GetPersonnages", { animeID: aniID }, function (data) {
            var resPerso = templatePerso(data);

            $('#PersoOutput').html(resPerso);
            $('#lstAni').html(resPerso);
        });
    }

    function AddCategorie(categorie) {
        $.getJSON("Animes/AddCategorie", { cat: categorie }, function (data) {
    });
}

</script>

<h2>Slideshow</h2>
<div id="slider1_container" style="position: relative; top: 0px; left: 0px; width: 600px; height: 300px;">
    <!-- Slides Container -->
    <div u="slides" style="cursor: move; position: absolute; overflow: hidden; left: 0px; top: 0px; width: 600px; height: 300px;">
        <div><img src="../imgs/elfen1.jpg" /></div>
    </div>
</div>


<h3>Catégories</h3>

<div id="CategoriesOutput">

</div>

<h3>Animes</h3>

<div id="AnimesOutput">

</div>

<h3>Personnages</h3>

<div id="PersoOutput">

</div>

<script id="CategoriesTemplate" type="text/x-handlebars-template">
    {{#each}}
    <h3 class="categories" onclick="GetAnimes({{CategoryID}})">{{CategoryNom}}</h3>
    {{/each}}
</script>

<script id="AnimesTemplate" type="text/x-handlebars-template">
    {{#each}}
    <h3 class="animes" onclick="GetPersonnages({{AnimeID}})">{{AnimeNom}}</h3>
    {{/each}}
</script>

<script id="PersoTemplate" type="text/x-handlebars-template">
    {{#each}}
    <h3 class="perso">{{PersonnageNom}}</h3>
    {{/each}}
</script>

【问题讨论】:

  • 我没有看到您的 AJAX 调用。你能发一下吗?或者也许我错过了什么......
  • 你的意思是这样的:$.getJSON(......... Daniel?
  • 现在看起来像这样:function AddCategorie(categorie) { $.getJSON("Animes/AddCategorie", { cat: categorie }, function (data) { }) 我只是不知道大括号之间放什么
  • 没错!我没有看到 POST 到 ~/AddCategorie 的调用,数据是否正确传递给方法?
  • 对于不会查看 cmets 的任何人,请将其添加到原始帖子 Joel =) 这也是正确的语法,您在哪里/如何调用您的函数 AddCategorie()?您可以手动点击该函数并查看它是否正在将数据传递给您的控制器吗?

标签: c# ajax angularjs


【解决方案1】:

首先,表单上不需要这个属性:

<form ng-model="AddCategorie()">

ng-model 只会在您使用 Angular 时发挥作用,而您似乎没有使用。另外,AddCategorie 目前没有明确的返回值,这意味着它的结果是undefined。因此,即使您使用的是 Angular,这也不是您想要的。


至于你的问题,我相信它的根源是你遇到了this problem with the browser's form submission taking precedence over your JavaScript

由于您的表单没有指定操作或方法,因此单击提交按钮将使用其默认操作和方法提交表单。这是返回当前 URL 的 GET。这就是为什么您在提交后在 URL 中看到 URL 更改为类似 Animes/Index?name=category 的内容,但您的 AddCategorie 操作没有被调用。

为了让它工作,我会修改表单如下:

<form id="add-categorie">
    <input type="text" id="nouvelle-categorie-nom" placeholder="Nouvelle catégorie" /><br />
    <input type="submit" value="Ajouter" />
</form>

然后,附加一个事件处理程序来监控表单的提交事件:

$('#add-categorie').on('submit', function(evt) {
  // This is the key line to prevent the default browser behavior of
  //  sending a GET back to the current URL.
  evt.preventDefault();

  var data = {
    // Did I get my Francias correct?
    cat: $('#nouvelle-categorie-nom').val();
  };

  // This should be a POST, not a GET (ala $.getJSON).
  $.post('/Animes/AddCategorie', data);
});

我还建议不要为此使用 GET,因为它不是幂等操作:

[HttpPost]
public void AddCategorie(string cat) {
    db.Categories.Add(new Category { CategoryNom = cat });
    db.SaveChanges();
}  

您不应该在此处使用 GET 而不是 POST 的实际和理论原因有一长串,但最直接给您带来麻烦的原因是浏览器缓存 GET 请求。

【讨论】:

    【解决方案2】:

    看起来您不是根据提供的代码发布的。您应该能够在 AddCategories 中设置调试标记并查看它是否正在使用该方法。比如:

    $.postJSON("Animes/AddCategorie",{ cat: 1 }, function (data) {
    
    });
    

    http://www.make-awesome.com/2012/11/jquery-postjson-method-for-asp-net-mvc/
    http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-json-data-code-example
    Angularjs $http.post, asp.net mvc controller gets null


    顺便说一句,如果您希望 AddCategorie 返回一个值,我希望它是一个 json 值,而不是 void。否则,将显示 alert("error"),而不是 "helloWorld"。不过,如果 Daniel 对此有任何意见,我很想听听。

    错误:(错误)

    public void AddCategorie(string cat)
            {
                Category category = new Category();
                category.CategoryNom = cat;
    
                //return Json(category, JsonRequestBehavior.AllowGet);
            }
    
    jQuery.getJSON("Search/AddCategorie", { cat: '2' }, function (data) {
        alert("helloWorld");
    }).error(function (data) {
        alert("error");
    });
    

    没有错误:(HelloWorld)

    public JsonResult AddCategorie(string cat)
            {
                Category category = new Category();
                category.CategoryNom = cat;
    
                return Json(category, JsonRequestBehavior.AllowGet);
            }
    
    jQuery.getJSON("Search/AddCategorie", { cat: '2' }, function (data) {
        alert("helloWorld");
    }).error(function (data) {
        alert("error");
    });
    

    如果您想无误地发布到 void:

    jQuery.post("Search/AddCategorie", { cat: '2' }, function (data) {
        alert("helloworld");
    }).error(function (data) {
        alert("error");
    });
    

    【讨论】:

    • 这怎么没用?
    • 虽然我同意调试是个好主意,但“试试这个”的答案应该发布在 cmets 中,而不是作为解决方案,并且 $.postJSON 在 angular 或 jquery 库中不作为函数存在,除非专门创建的它不会起作用。
    • 责备stackoverflow。我无法评论。 .....然后创建它,就像您创建它一样: $.ajax({ type: 'POST', url: '/form/', data: '{"name":"jonas"}', //或 JSON.stringify ({name: 'jonas'}), 成功: function(data) { alert('data: ' + data); }, contentType: "application/json", dataType: 'json' });
    猜你喜欢
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2013-08-26
    • 2015-05-12
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多