C# 如何使用AJAX和MVC将行插入数据库?

C# 如何使用AJAX和MVC将行插入数据库?,c#,ajax,angularjs,C#,Ajax,Angularjs,我有一个问题,我想使用C#MVC AJAX向我的数据库中添加一个新行,但它不起作用。我可以在URL中看到文本框的值作为参数,但当我单击submit按钮时,它不起作用,我不知道如何继续。你能帮我解决这个问题吗?以下是代码: 控制器中包含insert指令的我的方法: public void AddCategorie(string cat) { Category cate = new Category(); cate.CategoryNom = cat; db.Categori

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

控制器中包含insert指令的我的方法:

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=“猫的手势”;
}
@视图包。标题

索引中的代码(可能有帮助)显示应用程序的主页:

@{
    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>
@{
ViewBag.Title=“主页”;
}
@*
jQuery(文档).ready(函数($){
var options={$AutoPlay:true};
var jssor_slider1=新的$JssorSlider$('slider1_container',选项);
});
*@
.类别,.动画,.人物{
颜色:#000;
左边距:35px;
}
templateCategories=null;
templateAnimes=null;
templatePerso=null;
$(函数(){
templateCategories=handlebar.compile($('#CategoriesTemplate').html();
templateAnimes=handlebar.compile($('#AnimesTemplate').html();
templatePerso=handlebar.compile($('PersoTemplate').html();
$.getJSON(“动画/GetCategories”,null,函数(数据){
var结果=模板类别(数据);
$('#CategoriesOutput').html(结果);
});
});
函数GetAnimes(catID){
$.getJSON(“Animes/GetAnimes”,{categoryID:catID},函数(数据){
var resAnimes=模板动画(数据);
$('#AnimesOutput').html(重动画);
$('lstCat').html(重动画);
});
}
函数GetPersonnages(aniID){
$.getJSON(“动画/GetPersonnages”,{animeID:aniID},函数(数据){
var resPerso=templatePerso(数据);
$('#PersoOutput').html(resPerso);
$('#lstAni').html(resPerso);
});
}
函数AddCategorie(categorie){
$.getJSON(“Animes/AddCategorie”,{cat:categorie},函数(数据){
});
}
幻灯片
猫科动物
动画
人事
{{{#各}
{{CategoryNom}}
{{/每个}}
{{{#各}
{{AnimeNom}}
{{/每个}}
{{{#各}
{{PersonnageNom}}
{{/每个}}

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

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

});



顺便说一句,如果您希望AddCategorie返回一个值,我希望它是一个json值,而不是void。否则,将显示警报(“错误”),而不是“helloWorld”。不过,如果丹尼尔对此有任何评论,我很乐意听听

错误:(错误)

非错误:(HelloWorld)

如果您希望在没有错误的情况下发布到void:

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

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

<form ng-model="AddCategorie()">
然后,附加事件处理程序以监视表单的提交事件:

$('#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-here而不是POST,有一长串的实际和理论原因,但最直接给您带来麻烦的是浏览器缓存GET请求。

我看不到您的AJAX调用。你能把它寄出去吗?或者我遗漏了一些东西……你的意思是:$.getJSON(……Daniel?现在看起来是这样的:函数AddCategorie(categorie){$.getJSON(“Animes/AddCategorie”,{cat:categorie},函数(data){})我只是不知道在大括号之间到底放什么!我没有看到一个传递到~/addCategine的调用,数据是否正确地传递到该方法?请将它添加到原始的post Joel中,以供不查看注释=)的人使用。这也是正确的语法,您在哪里/如何调用函数addCategine()?你能手动点击这个函数,看看它是否在向你的控制器传递数据吗?这怎么没用?虽然我同意调试是个好主意,“试试这个”答案应该在注释中发布,而不是作为解决方案发布,并且$.postJSON在angular或jquery库中不作为函数存在,除非专门创建它,否则它将不起作用。责怪stackoverflow。我不能评论……然后创建它,就像创建:$.ajax({type:'POST',url:'/form/',data:'{“name”:“jonas”}、//或JSON.stringify({name:'jonas'}),成功:函数(数据){alert('data:'+data);},contentType:“application/JSON”,数据类型:'JSON'});
<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);
});
[HttpPost]
public void AddCategorie(string cat) {
    db.Categories.Add(new Category { CategoryNom = cat });
    db.SaveChanges();
}